I have some checkboxes bound to an array in my model. This works great, when you check a box the array is updated accordingly.
However when the value has changed i wish to call a method on my model to filter the results given the new values. I have tried hooking up the change event but this seems to have the values prior to the change rather than after the change.
I have illustrated my issue in a jsfiddle http://jsfiddle.net/LpKSe/ which might make this make more sense.
For 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>
You don't need the change event. If you subscribe to the observableArray you will be notified when it changes, and be passed 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);
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With