Search code examples
knockout.jsknockout-mapping-pluginko.observablearray

knockout mapping + add to observable array


Fiddle can be found here.

I'm adding to an observable array which is mapped by ko.mapping.fromJS().

In my view I'm building a URL by using a property on the array attr: { href: '/Users/Summary?userId=' + ID() }.

If I want to add an item to the array I'm using self.Users.push().

If I do that I get an error of ID is not a function.

So my question is whats the correct way of adding an item to the array, or am I not building the href attr properly?


Solution

  • It seems like you are trying to push a plain object (without observables). You need first construct it, or map it to obsevables.

    self.Users.push(new User(data));
    

    or

    self.Users.push(ko.mapping.fromJS(data, mapping));
    

    Another alternative would be to just remove the () from the expression. But then the observable ID-properties will behave strangly.