javascript - KnockoutJS cannot delete object from observableArray -


i have following code:

var testvm = {   things: ko.observablearray([     { id: 1, name: "apple" },     { id: 2, name: "banana" },     { id: 3, name: "orange" },     { id: 4, name: "pineapple" },     { id: 5, name: "pear" }     ]),    deletething: function (data) {     var things = testvm.things;     var index = things.indexof(data);      // debug...     console.log('data', data);     console.log('index', index);      if (index > -1) {         things.splice(index, 1)     }   },    deleteapple: function () {     this.deletething({ id: 1, name: "apple" });   }  };  ko.applybindings(testvm); 

with html:

<ul data-bind="foreach: things">   <li>     <a data-bind="click: $root.deletething">x</a>&nbsp;|&nbsp;     <span data-bind="text: name"></span>   </li> </ul> <a data-bind="click: deleteapple">delete apple</a> 

which i've created in fiddle. issue i'm having when invoked data-bind="click: deletething" inside foreach deletething function works fine, if (in case of deleteapple method) attempt manually delete never finds index , subsequently doesn't delete item observablearray.

i'm stumped because in both instances console.log shows same data.

the issue having related object references. in deleteapple function passing new object not match original object reference.

the remove api accept function passes item in can return truthy/falsy whether want remove item.

example of using remove on observablearray:

deleteapple: function () {     this.things.remove(function(item) {        return item.id === 1 && item.name === "apple";        }); } 

updated fiddle: http://jsfiddle.net/rniemeyer/5hpxz/


Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -