Question

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

Was it helpful?

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/

OTHER TIPS

The problem was that you didn't have a curly brace in there. Check your console next time -

http://jsfiddle.net/9JsUJ/9/

self.removeItem = function () 
    self.allItems.remove(this);
};

The fiddle has included the fix and your fiddle is working.

self.removeItem = function () {
    self.allItems.remove(this);
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top