Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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>
like image 953
Hoppe Avatar asked Apr 20 '12 19:04

Hoppe


1 Answers

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.

like image 71
RP Niemeyer Avatar answered Sep 21 '22 19:09

RP Niemeyer