I am currently having an issue extending my ObserableArray objects so they have extra observables attributes.
What I am trying to do is something like this:
ko.utils.arrayForEach(MyKnockoutManager.GetByModelKeyName('Catalog'), function (CatalogItem) { CatalogItem.IsSelected = ko.observable(false); });
However, that of course is not the case.
Is there any way to add observables to obserableArray's objects?
To add an additional property all you need to do is set it -
CatalogItem.IsSelected = ko.obsrevable(false);
That will add an additional property onto the object just like you want. If you are trying to add it onto every object then why not add it when the object is constructed?
function catalogItemModel(item) {
var self = this;
self.Id = ko.observable(id);
self.Name = ko.observable(name);
self.someOtherPropertyLikeIsSelected = ko.observable(false);
}
var thisArray = ko.observableArray();
var thisData = [{ id: 1, name: 'Jim' }, { id: 2, name: 'Bob' }];
$.each(thisData, function (index, item) {
new catalogItemModel(item);
});
Using a model ensures consistency between all of your observables passed in. You can also use use prototypes to add the functions after the data has been mapped but I don't think that is what you are looking for.
Edit
I see what you are saying about iterating through the items to add the property but it's not really the right direction you want to take. If you must do so just adjust your code to the following -
var vm.CatalogItems = ko.observable(MyKnockoutManager.Items.slice());
ko.utils.arrayForEach(vm.CatalogItems(), function (CatalogItem) {
CatalogItem.IsSelected = ko.observable(false);
});