Knockout点击数据绑定

时间:2014-06-02 13:31:43

标签: javascript jquery knockout.js

我在下面的例子中有一个问题

HTML CODE

 <table id="items">
    <thead>
        <tr>
            <td>ToDo List</td>
        </tr>
    </thead>
    <tbody data-bind="foreach: toDoItems">
        <tr>
            <td><label data-bind="text: toDoItem"></label></td>
            <td><a href="#" data-bind="click: $root.removeToDoItem">Remove</a></td>
        </tr>
    </tbody>
</table>
Add item: <input type="text" id="newitem" />
<button data-bind="click: addnewItem">Add</button>



这是我的JS代码

$(function () {

  var MetalViewModel = function() {
    var self = this;
    self.toDoItems = ko.observableArray();

    self.update = function() {
        self.toDoItems.removeAll();
        self.toDoItems.push(
            new metals({"Task":"This is urgent task."}),
            new metals({"Task":"You need to do it also."})
        );
    }
    self.addnewItem = function () {
        alert( $("#newitem").val() );
        self.toDoItems.push(
            new metals({"Task":$("#newitem").val()})
        );
    };
    self.removeToDoItem = function(item) {
        self.toDoItems.remove(item);
    };

  };

var MetalViewModel = new MetalViewModel();
var y = window.setInterval(MetalViewModel.update,1000);
ko.applyBindings(MetalViewModel, document.getElementById("items"));

});
var metals = function (data) {
    return {
        toDoItem: ko.observable(data.Task)
    };
};

一切都很好。清单,删除....

我面临的唯一问题是,当我添加新项目时,功能完全不起作用...意味着即使我提醒点击绑定也没有到达那里。

2 个答案:

答案 0 :(得分:2)

您只使用您的vewmodel(id=items)绑定了表:

 ko.applyBindings(MetalViewModel, document.getElementById("items"));

并且您的按钮位于表格之外,因此它与您的视图模型无关。

作为解决方案,您可以绑定到公共父级或整个页面:

 ko.applyBindings(MetalViewModel);

答案 1 :(得分:1)

这里有两个问题:

  • 无效绑定,而非ko.applyBindings(MetalViewModel, document.getElementById("items"));应为ko.applyBindings(MetalViewModel);
  • 无效data-bind函数名称而非additemToAdd应为addToDoItem

此处正在工作sample

相关问题