本文介绍了无法解析绑定.剔除错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我学习淘汰赛的第二天.

this is my day 2 learning Knockout.

尝试为按钮单击附加"deleteItem".它给出了以下错误.

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

未捕获的错误:无法解析绑定.
消息:ReferenceError:deleteItem未定义;绑定值:单击:deleteItem

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

JavaScript:

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>

推荐答案

函数deleteItem在您的视图模型上.在foreach内部进行绑定时,绑定操作的上下文是listItem数组中的单个item.您需要绑定到$root.deleteItem才能引用根视图模型.

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.

这篇关于无法解析绑定.剔除错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 19:39