3

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

问题

  1. 单击时:未调用 pendDeleteItem。我找不到范围;(
  2. 在 PendDeleteItem 我有这个问题。我需要访问 PendingItem 属性。

工作小提琴:http: //jsfiddle.net/ThomasDeutsch/j7Qxh/8/

目标

单击后,项目将发送到 PendingItem。

限制:如果可能,我想保留 ko.applyBindings(ViewModel),因为我想添加更多存储库并在 html 中定义数据绑定,例如:customer.pendDeleteItem

4

2 回答 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在单击处理程序中是指“项目”,而不是视图模型。您将需要更改这些行:

this.PendingItems.push(item);
this.Items.remove(item);

要引用您的视图模型:

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

这是一个更新的小提琴

于 2012-06-07T08:51:25.467 回答
1

对于第二个问题:此绑定将解决它:

data-bind="click: function() { $root.customer.pendDeleteItem($data)}

这是相应的js,我可以用“this”引用它:)

pendDeleteItem = function(item) {
        console.log("pendDeleteItem called");
        item.Operation = 'DELETE';
        this.PendingItems.push(item);
        this.Items.remove(item);
    };
于 2012-06-07T09:31:14.783 回答