I use knockoutjs.mapping to map an existing object return be the server is JSON.
The object is similar to the cart editor example, the main difference in the items already exists.
Here is my attempt http://jsfiddle.net/9ej3r/
mapping is straight-forward:
var mapping = {
'Items': {
create: function(options) {
return new InvoiceItem(options.data);
},
key: function(data){
return ko.utils.unwrapObservable(data.ID);
}
}
};
when i click remove, i get the error: “this.Items in undefined”
what am i doing wrong here? how can adapt the cart editor example to work with existing lines ?
You have been bitten by the fact how
thisworks in javascript.Because when your
removeItemmethod gets called thethiswill be the actual item e.g. anInvoiceItemnot theInvoiceso you need to capture the “other”thisin a variable and use that in your function to access theInvoice.So your
removeItemshould look like this:See also this Demo.
You should note that the cart editor example also uses this technique in the
removeLinemethod