Replacing item in observableArray

痞子三分冷 提交于 2019-12-02 19:05:51

The replace function accepts two parameters, the item you want to replace and the new item you want to replace it with. You are passing in the index in place of the item to replace so it doesn't work.

The replace call should be:

self.locations.replace(oldLocation, new location(value));

On a side note, you shouldn't need the valueHasMutated() call there, it will get invoked by the replace() call.

I simply want to mention an alternative way to do it:

self.locations.splice(
  self.locations.indexOf(location),   // Index of the 1st element to remove
  1,                                  // Number of elements to remote at this index
  new fizi.ko.models.location(value)  // A param for each element to add at the index
);

Knockout includes splice in its documentation, but doesn't include replace: Knockout Obervable Arrays Docs. However, if you look at the source code you'll see that both functions are implemented (at least in KO 3.0, I don't know if replace was missing in previous versions).

Paul Manzotti

I'm not aware of a replace method in JavaScript for arrays, or in Knockout. Am I missing something?

If you want to use your second method, then you need to access locations as an observable:

self.locations()[self.locations.indexOf(location)] = new fizi.ko.models.location(value);
self.locations.valueHasMutated();

though you don't when using indexOf, as there is a Knockout version of that for observable arrays.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!