Unable to parse bindings. knockout error

2019-02-26 08:45发布

问题:

this is my day 2 learning Knockout.

Trying to attach "deleteItem" for button click. it gives the following error.

Error

Uncaught Error: Unable to parse bindings.
Message: ReferenceError: deleteItem is not defined; Bindings value: click: deleteItem

JavaScript:

$(function () {
    var defaultData = [{
        id: 1,
        item: "Todo 1"
    }, {
        id: 2,
        item: "Todo 2"
    }, {
        id: 3,
        item: "Todo 3"
    }];
    var viewModel = {
        listItem: ko.observableArray(defaultData),
        addItem: function () {
            // Add new item
            var id = this.listItem().length + 1;
            this.listItem.push({
                id: id,
                item: "Todo " + id
            });
        },
        deleteItem: function () {
            alert(this);
        }
    }
    ko.applyBindings(viewModel, main);
});

HTML:

<div id="main">
    <button data-bind="click: addItem">+ Add Item</button>
    <div data-bind="foreach: listItem">
        <input type="text" data-bind="value: item" />
        <input type="button" data-bind="click: deleteItem" />
        <br />
    </div>
</div>

回答1:

The function deleteItem is on your view model. When you're binding inside the foreach, the context of the binding operation is the individual item from the listItem array. You need to bind to $root.deleteItem to reference the root view model.



标签: knockout.js