Knockout event changed

I have some flags tied to an array in my model. This works great when you check the box, the array is updated accordingly.

However, when the value has changed, I want to call a method on my model to filter the results based on the new values. I tried attaching a change event, but this seems to matter before the change, not after the change.

I illustrated my problem in jsfiddle http://jsfiddle.net/LpKSe/ , which might make this more reasonable.

For the sake of completeness, my code is repeated here.

Js

function SizeModel() { var self = this; self.sizes = ko.observableArray(["small", "medium", "large"]); self.sizes2 = ko.observableArray(["small", "medium", "large"]); self.getResults = function(e) { alert(self.sizes()); }; self.getResults2 = function(e) { alert(self.sizes2()); }; } $(document).ready(function() { sizeModel = new SizeModel(); ko.applyBindings(sizeModel); });​ 

HTML

 <h3>Size <input type="checkbox" value="small" data-bind=" checked: sizes, event:{change: getResults}"/> <span class='headertext'>Small</span> <input type="checkbox" value="medium" data-bind=" checked: sizes, event:{change: getResults}" /> <span class='headertext'>Medium</span> <input type="checkbox" value="large" data-bind=" checked: sizes, event:{change: getResults}" /> <span class='headertext'>Large</span> </h3> <h3>Size <input type="checkbox" value="small" data-bind=" checked: sizes2, event:{click: getResults2}"/> <span class='headertext'>Small</span> <input type="checkbox" value="medium" data-bind=" checked: sizes2, event:{click: getResults2}" /> <span class='headertext'>Medium</span> <input type="checkbox" value="large" data-bind=" checked: sizes2, event:{click: getResults2}" /> <span class='headertext'>Large</span> </h3> 
+4
source share
2 answers

You do not need a change event. If you subscribe to an observable array, you will be notified when it changes, and submit the updated array: http://jsfiddle.net/jearles/LpKSe/53/

 function SizeModel() { var self = this; self.sizes = ko.observableArray(["3", "2", "1"]); self.sizes.subscribe(function(updated) { alert(updated); }); } 
+14
source

In your script, you do not have enough commas in data-bind -s, here is an example: http://jsfiddle.net/4aau4/1/

Go to the problem - it could be either a KnockoutJS-related issue (i.e. it updates the observable array after the change event is change ), or something similar to what I got stuck a while ago: Checkboxes are checked before the handler clique is even called

EDIT:

What a hard Sunday, I think I'm still not awake :)

Take a look at this snippet: http://jsfiddle.net/4aau4/2/ - it looks like the DOM is updated correctly, and ko.observableArray lagging. ( $('input:checked').length indicates how many flags are actually checked).

0
source

All Articles