Reputation: 3
I've been struggling on this for a while now, trying many different unsuccessful methods. I'll spare you all of the attempts I've tried and show you what I'm working with. It looks like this..
// Retrieve unique list of items
self.items= ko.observableArray([]);
$.ajax({
url: self.options.itemsURL,
data: {},
dataType: "json",
success: function (data) {
data = data || {};
self.items(data);
self.items.unshift({"packet": "All","checked": "true"});
}
});
After the success the data seems to be passed into the self.items array. Then a new element is added to the top of the array named "All".
This is working just fine for generating a list of items with checkboxes for me. However, I need to be able to monitor and access the data to know when someone has checked boxes, know which boxes were checked, and to modify the values of the boxes if need be. By default the "All" selection is checked. If someone checks another box, I'd like the "All" box to become unchecked. So far I've been unsuccessful in all attempts of monitoring these arrays, but I don't understand this style of programming very well. Could someone point me in the right direction for this issue?
Thanks
Upvotes: 0
Views: 699
Reputation: 33379
To essentially elaborate on @Daniel's answer, your code might look something like:
//Constructor for a regular list item
function ListItem(itemData) {
this.checked = ko.observable(false);
this.checked.subscribe(function () {
//Do something when this is checked or unchecked
});
}
//Constructor for that "all" list item
function ListItemAll() {
this.checked = ko.observable(true);
this.checked.subscribe(function () {
//Do something when this is checked or unchecked
});
}
// Retrieve unique list of items
self.items= ko.observableArray([]);
$.ajax({
url: self.options.itemsURL,
data: {},
dataType: "json",
success: function (data) {
data = data || [];
//Create viewModels from the data
var itemViewModels = data.map(funtion(itemData) {
return new ListItem(itemData);
});
self.items([new ListItemAll()].concat(itemViewModels));
}
});
You could drop the constructors and just do the logic for each item inline; but the main point is that you're going to want observables for the checked/unchecked state for each item in the data.
Upvotes: 0
Reputation: 7742
Your problem is that knockout observable arrays tracks which objects are in the array, not the state of those objects (documentation).
Instead of passing into the observable array normal javascript objects, create from those objects observables and pass them to the array. Then you'll be able to observe any of the changes in the state of the objects...
Upvotes: 1