knockout.js - checkbox state propogating incorrectly from model to UI -


funny things happening in ui using knockout bindings.

ui defined follows:

<ul id="items" data-bind="foreach: items">     <li>                 <input type="checkbox" data-bind="checked: $root.selecteditems, value: $data, click: $root.itemschanged"/>         <label data-bind="text: $data"></label>     </li> </ul>  <div data-bind="foreach: selected">     <p data-bind="text:$data"></p> </div> 

js included in head portion goes like:

function viewmodel(items) {     var self = this;     self.items = ko.observablearray(items);     self.selecteditems = ko.observablearray([]);     self.itemschanged = function () {         self.selected.removeall();         self.selecteditems().foreach(function (e) {             self.selected.push(e);         });     };     self.selected = ko.observablearray([]); }  var model = new viewmodel(['read paper', 'clear room', 'cook food', 'buy rice']); window.onload = function () {     ko.applybindings(model); }; 

what expect: when check first checkbox, should show checked state, , div should correctly populated checked item.

what observe: when check first checkbox, doesn't checked. div below populates correctly. check checkbox, first checkbox clicked gets checked; 1 clicked doesn't checked. div reflects item.

am doing wrong?

fiddle use: http://jsfiddle.net/deostroll/bnfkf/

when using checked binding click binding need return true click handler to trigger browsers default behavior in order checkboxes checked correctly:

self.itemschanged = function () {     self.selected.removeall();     self.selecteditems().foreach(function (e) {         self.selected.push(e);     });     return true; }; 

demo jsfiddle.

but code in itemschanged not needed because ko track selected items in selecteditems array there no need copy it. use can use directly:

<ul id="items" data-bind="foreach: items">     <li>                 <input type="checkbox"               data-bind="checked: $root.selecteditems, value: $data"/>         <label data-bind="text: $data"></label>     </li> </ul>  <div data-bind="foreach: selecteditems">     <p data-bind="text:$data"></p> </div> 

and in viewmodel don't need itemschanged function:

function viewmodel(items){     var self = this;     self.items = ko.observablearray(items);     self.selecteditems = ko.observablearray([]);            self.selected = ko.observablearray([]); } 

demo jsfiddle.


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -