13

使用 KnockoutJS,如何从可观察数组中删除项目?我希望能够单击列表项,然后从数组(以及列表)中删除该项目。

下面的代码示例报告:“this.expertise 未定义”。

我是否需要定义某种专业知识对象,然后从那里调用它?

<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>
4

1 回答 1

17

当您从子级调用方法时,this将设置为子级而不是$parent.

有很多方法可以确保removeExpertise调用this. 一个简单的方法是使用.bind.

它看起来像:

this.removeExpertise = function (expertise) {
    this.expertise.remove(expertise);
}.bind(this);

Also, you will want expertise to be an observableArray rather than an observable, as an observableArray exposes array manipulation methods including a remove function.

于 2012-04-20T20:25:53.343 回答