0
votes

I am trying to add a computed to a child view model which is populated using the Knockout mapping. When I break in I see the role array populated correctly in the javascript array but in my view model the observable array is always length 0.

Here is a jsfiddle that shows it. Any help on what i am missing would be appreciated.

http://jsfiddle.net/spbrogan/aREpY/

Here is the child view model

var userModel = function(data) {
    data.createDate = new Date(data.createDate);

    ko.mapping.fromJS(data, {}, this);


    this.isAdmin = ko.computed(function() {
        var admin = false;
        ko.utils.arrayForEach(this.role(), function(role) {
            if(role.name == "Admin") {
                admin = true;
             }
         });
         return admin;
    }, this);
} //close userModel

Thanks

1

1 Answers

0
votes

After the mapping has run it creates observables from your JS - not just the root object, but all properties inside it. An observable is a function, so you need to access name using the () form:

ko.utils.arrayForEach(this.role(), function(role) {
    if(role.name() == "Admin") {
         admin = true;
    }
});

Here is an updated fiddle: http://jsfiddle.net/aREpY/41/