0

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?

1 Answer 1

1

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);
});
Sign up to request clarification or add additional context in comments.

2 Comments

I was having difficulty adding a new property because I was using the knockout mapping plug-in. I tried using the mapping options but was unable to get the mapping value to stick. Otherwise, the construction of the model beforehand would have been the optimal choice.
I don't quite understand - just override the mapping and add the property, or do exactly what you are trying to in your question and iterate through the options and add a property.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.