Search code examples
knockout.jsko.observablearray

can't remove items from an observable array


I have a part of code on jsFiddle here. Can someone say me what's wrong with 'removeItem' function?

HTML

<div id="newIdea" data-bind="if: isNew">   
<div data-bind="with: idea">
           <input type="text" style="width: 200px;"
            data-bind='value:wanted().itemToAdd, valueUpdate: "afterkeydown"' />
            <input type="button" data-bind="click:wanted().addItem" value="add" />
    <ul data-bind="foreach: wanted().allItems">
        <li>
           <span data-bind="text:$data"></span>
           <input type="button" 
           data-bind="click:$parent.wanted().removeItem"  value="remove"/>
        </li>
    </ul> 
</div>
</div>

JavaScript

var WantedListModel = function () {
    var self = this;
    self.itemToAdd = ko.observable("");
    self.allItems = ko.observableArray();
    self.addItem = function () {
        var item = self.itemToAdd();
        self.allItems.push(item);
        self.itemToAdd("");
    };
    self.removeItem = function () {
         self.allItems.remove(this);
    };
};

var vm = {
     isNew: ko.observable(true),
     idea: ko.observable({
         wanted: ko.observable(new WantedListModel())
     })
};
ko.applyBindings(vm);

I have to use such a hierarchy


Solution

  • Ko passes current element as first parameter of the function so you should use it instead of this:

    self.removeItem = function (data) {
        alert(data);
        self.allItems.remove(data);
    };
    

    Here is working fiddle: http://jsfiddle.net/9JsUJ/8/