javascript - Knockoutjs error: You cannot apply bindings multiple times to the same element -
i'm trying automatically populate element in existing web page can't change , page uses knockoutjs. input element looks more or less:
<input maxlength="8" id="xxx" data-bind="textinput: otcinput" type="tel">
then use knockoutjs attempt unbind textinput , populate input element dynamically whatever value need, do:
ko.cleannode($('#xxx')); ko.applybindings({ otcinput: ko.observable("123") // populate myself });
however, leads error you cannot apply bindings multiple times same element
... question why? i'm cleaning node ... or not? there way using knockoutjs see whether there dangling bindings or leftovers in way while trying execute "overriding" ko.applybindings
?
i have tried other ways set input value via jquery sendkeys plugin without success i.e.
$('#xxx').sendkeys('123'); // nothing happens
i tried:
$('#xxx').unbind(); $('#xxx').off(); $('#xxx').sendkeys('123'); // again nothing happens
you're passing jquery object cleannode
. applybindings
, has dom element, not jquery object. so:
ko.cleannode($('#xxx')[0]); // -------------------^^^
example — fails:
ko.applybindings({ foo: ko.observable("one") }, $("#test")[0]); ko.cleannode($("#test")); ko.applybindings({ foo: ko.observable("two") }, $("#test")[0]);
<div id="test"> <div data-bind="text: foo"></div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
...but (with [0]
) works:
ko.applybindings({ foo: ko.observable("one") }, $("#test")[0]); ko.cleannode($("#test")[0]); ko.applybindings({ foo: ko.observable("two") }, $("#test")[0]);
<div id="test"> <div data-bind="text: foo"></div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
i have tried other ways set input value
if that's goal, don't have muck bindings (which have undesirable effects), just:
$("#xxx").val("new value").trigger("change");
the trigger("change")
necessary ko see change , update observable. (or it's textinput
binding, might use input
rather change
.)
example — fails:
// previously-bound stuff: var vm = { foo: ko.observable("foo") }; ko.applybindings(vm, document.body); // prove observable , input in sync: console.log("check1", vm.foo(), $("#test").val()); // update field $("#test").val("updated").trigger("change"); // prove observable , input still in sync: console.log("check2", vm.foo(), $("#test").val());
<input id="test" type="text" data-bind="textinput: foo"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
Comments
Post a Comment