最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - KnockoutJS remove item from observable array. Item is listitem within ul, which was generated by foreach - Stack Ov

programmeradmin1浏览0评论

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).

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>

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).

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>
Share Improve this question edited May 20, 2014 at 13:06 Hoppe asked Apr 20, 2012 at 19:58 HoppeHoppe 6,80518 gold badges64 silver badges122 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 17

When you call a method from the child, this will be set to the child rather than $parent.

There are many ways to ensure that removeExpertise is called with the appropriate value for this. An easy way is to use .bind.

It would look like:

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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论