Reputation: 48
I am relatively new to knockoutjs, but I seem to be having a problem with an observableArray of checkboxes, the checkboxes have some observable properties for checked, and disabled.
Using knockout I can check and uncheck the box, but it seems that once I interact with the checkbox manually (IE by clicking it with the mouse) the underlying data seems to be changing but I can't use knockout to check or uncheck the box anymore.
HTML
<div id="filterByPrice" data-bind="foreach: priceFilters">
<div>
<input type="checkbox" data-bind="attr: {id: $index, value: value, checked: checked, disable: disabled}" />
<span data-bind="text: label"></span>
</div>
</div>
Javascript
function FilterBy(name, value, label) {
this.name = name;
this.value = value;
this.label = label;
this.disabled = ko.observable(false);
this.checked = ko.observable(false);
}
$(function () {
var viewModel = {
priceFilters: ko.observableArray([
new FilterBy("price0", "0", "All Prices")])
};
ko.applyBindings(viewModel);
});
http://jsfiddle.net/paulwilliams0/EYEz2/
Is there something that I am doing that is wrong? Not only am I new to knockout, but I am new to MVVM in general. Thanks a lot
Upvotes: 0
Views: 333
Reputation: 2060
here i have a working version of your example:
http://jsfiddle.net/infantrash/hVac2/2/
data-bind attribute for your checkbox: use the build-in binding handlers, attr: { id: $index } is ok, but value, checked and disable are should not be in the curly brackets.
use knockout functions for your functionality instead of mixing jQuery into it.
function viewModel(){
var self = this;
self.priceFilters = ko.observableArray([
new FilterBy("price0", "0", "All Prices"),
new FilterBy("price1", "1", "1st Price")
]);
self.checkAllPrices = function(){
ko.utils.arrayForEach(self.priceFilters(), function(item){
item.checked(true);
})
};
self.unCheckAllPrices = function(){
ko.utils.arrayForEach(self.priceFilters(), function(item){
item.checked(false);
})
};
}
i changed the viewModel to a function instead of using the object literal notation, but that's just my preferred way, you can use the object literal notation if you want.
Upvotes: 1