Knockout.js:使用存储库模式在单击事件上绑定到函数的绑定

3

我在尝试在Knockout.js中实现Repository-Pattern时遇到了困难。我发现很难处理点击事件,因为:

问题

  1. 点击时,不会调用pendDeleteItem。我找不到作用域 ;(
  2. 在PendDeleteItem中,我有一个this问题。我需要访问PendingItem属性。

有效示例http://jsfiddle.net/ThomasDeutsch/j7Qxh/8/

目标

点击时,项目将被发送到PendingItem。

限制:如果可能的话,我想保留ko.applyBindings(ViewModel),因为我想添加更多Repositories并在html中定义data-bind,例如:customer.pendDeleteItem。

2个回答

2
你的问题的第一部分很简单。看一下你按钮的标记:
<button data-bind"click: $root.customer.pendDeleteItem "> sendTo -> PendingItems</button>

你在 data-bind 属性名后面漏了一个 =。请将它改为这样:
<button data-bind="click: $root.customer.pendDeleteItem "> sendTo -> PendingItems</button>

下一个问题是,单击处理程序中的this指的是“item”,而不是视图模型。您需要更改这些行:
this.PendingItems.push(item);
this.Items.remove(item);

引用您的视图模型:

ViewModel.customer.PendingItems.push(item);
ViewModel.customer.Items.remove(item);

这里有一个更新的fiddle


我想在我的ViewModel中添加几个Repositorys,因此无法通过名称在ViewModel中引用对象。有解决方案吗?谢谢你的帮助! - Thomas Deutsch

2
第二个问题可以通过以下绑定来解决:
data-bind="click: function() { $root.customer.pendDeleteItem($data)}

这是相应的 JavaScript 代码,我可以使用 "this" 来引用它 :)
pendDeleteItem = function(item) {
        console.log("pendDeleteItem called");
        item.Operation = 'DELETE';
        this.PendingItems.push(item);
        this.Items.remove(item);
    };

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接