Javascript KnockoutJS 从 observable 数组中删除项目。item是ul内的listitem,由foreach生成
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10252749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
KnockoutJS remove item from observable array. Item is listitem within ul, which was generated by foreach
提问by Hoppe
Using KnockoutJS, how can I remove an item from an observable array? I want to be able to click on the listitem, and remove the item from the array (and thereby the list).
使用 KnockoutJS,如何从可观察数组中删除项目?我希望能够单击列表项,然后从数组(以及列表)中删除该项。
The code sample below reports: 'this.expertise is undefined'.
下面的代码示例报告:'this.expertise is undefined'。
Do I need to define some sort of expertise object, and then call it from within there?
我是否需要定义某种专业知识对象,然后从那里调用它?
<ul data-bind="foreach: expertise">
<li data-bind="text: Key, click: $parent.removeExpertise"></li>
</ul>
<script type="text/javascript">
$(function () {
function AppViewModel() {
this.removeExpertise = function (expertise) {
this.expertise.remove(expertise);
};
this.expertise = ko.observable([
{ Key: 'Charles', Value: 'Charlesforth' },
{ Key: 'Denise', Value: 'Dentiste' }
]);
}
// Activates knockout.js
jQuery(document).ready(function () {
ko.applyBindings(new AppViewModel());
});
});
</script>
回答by RP Niemeyer
When you call a method from the child, thiswill be set to the child rather than $parent.
当您从子级调用方法时,this将设置为子级而不是$parent.
There are many ways to ensure that removeExpertiseis called with the appropriate value for this. An easy way is to use .bind.
有很多方法可以确保removeExpertise使用 的适当值调用this。一个简单的方法是使用.bind.
It would look like:
它看起来像:
this.removeExpertise = function (expertise) {
this.expertise.remove(expertise);
}.bind(this);
Also, you will want expertiseto be an observableArrayrather than an observable, as an observableArrayexposes array manipulation methods including a removefunction.
此外,您将希望expertise成为 anobservableArray而不是 an observable,因为 anobservableArray公开了包括remove函数在内的数组操作方法。

