KnockoutJS从可观察数组中删除项目。项目是ul中的listitem,由foreach生成 [英] KnockoutJS remove item from observable array. Item is listitem within ul, which was generated by foreach
问题描述
使用KnockoutJS,如何从可观察数组中删除项?我希望能够点击listitem,并从数组中删除该项(从而删除列表)。
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).
下面的代码示例报告:'this.expertise未定义'。
The code sample below reports: '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>
推荐答案
当你从孩子那里调用一个方法时,此
将设置为子项而不是 $ parent
。
When you call a method from the child, this
will be set to the child rather than $parent
.
有很多方法可以确保使用适当的值调用
。一种简单的方法是使用 removeExpertise
.bind
。
There are many ways to ensure that removeExpertise
is called with the appropriate value for this
. An easy way is to use .bind
.
它看起来像:
this.removeExpertise = function (expertise) {
this.expertise.remove(expertise);
}.bind(this);
此外,您还需要专业知识
一个 observableArray
而不是 observable
,作为 observableArray
公开数组操作方法,包括 remove
函数。
Also, you will want expertise
to be an observableArray
rather than an observable
, as an observableArray
exposes array manipulation methods including a remove
function.
这篇关于KnockoutJS从可观察数组中删除项目。项目是ul中的listitem,由foreach生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!