jquery - Knockout $root binding does not update UI element immediately -
i want display $root
on page know what's in object. after first add event, added item added object, ui not reflect change. on second add event, first item displayed on ui, second 1 not displayed until third add event , forth.
html
<input type='text' data-bind='value: selecteditem' /> <input type='button' data-bind='click: additem' value='add' /> <pre>vm = <span data-bind="text: ko.tojson($root, null, 4)"></span></pre>
js
$(document).ready(function () { var basevm = function () { var = {}; return that; }; var testvm = function () { var = basevm(); that.relateditems = ko.observablearray(['pork', 'ham']); that.selecteditem = ko.observable(''); that.additem = function () { if (that.relateditems().indexof(that.selecteditem()) >= 0) { alert('existed'); } else { that.relateditems().push(that.selecteditem()); } }; that.removeitem = function () { if (that.relateditems().indexof(that.selecteditem()) >= 0) { that.relateditems().remove(that.selecteditem()); } }; return that; }; var vm = testvm(); ko.applybindings(vm); });
you're calling .push
(and .remove
) on underlying javascript array, knockout doesn't see change. it's when else causing whole thing rerender picks changes.
knockout redefines array functions on observablearrays, , when call them on objects, both updates underlying array , notifies subscribers. instead of this:
that.relateditems().push(that.selecteditem());
you need this:
that.relateditems.push(that.selecteditem());
here changes:
$(document).ready(function () { var basevm = function () { var = {}; return that; }; var testvm = function () { var = basevm(); that.relateditems = ko.observablearray(['pork', 'ham']); that.selecteditem = ko.observable(''); that.additem = function () { if (that.relateditems().indexof(that.selecteditem()) >= 0) { alert('existed'); } else { that.relateditems.push(that.selecteditem()); } }; that.removeitem = function () { if (that.relateditems().indexof(that.selecteditem()) >= 0) { that.relateditems.remove(that.selecteditem()); } }; return that; }; var vm = testvm(); ko.applybindings(vm); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script> <input type='text' data-bind='value: selecteditem' /> <input type='button' data-bind='click: additem' value='add' /> <pre>vm = <span data-bind="text: ko.tojson($root, null, 4)"></span></pre>
Comments
Post a Comment