我需要一种干净的方法来访问 foreach 中的父作用域

I need a clean way to access parent scope in knockout foreach

我有很多地方使用了敲除数据绑定的 foreach 循环。一个很好的例子是项目列表,右侧有一个显示 "edit" 的点击按钮。我发现自己编写的代码如下所示:

<div data-bind="foreach: myListData">
    ... other divs ...
    <button data-bind="click: $parent.editItem.bind($data)">View</button>
</div>

editItem 函数将如下所示:

editItem: function (review, data) {
    window.location = "/item/edit/" + review.Id();
},

我发现使用 $parent 是一种反模式,而且我还认为在同一行上使用 .bind 和仅用于淘汰赛的 $data 是相当神秘的,尤其是如果开发人员并不十分熟悉淘汰赛。

是否有更好、更简洁的方法来在 foreach 的淘汰赛中编写父作用域访问函数?

您可以将 editItem 函数放在每个评论上,或者传递对定义了 editItem 函数的视图模型的引用。

我还没有测试过下面的示例,但它应该会给你一个想法。

function Review(review, vm) {
    var self = this;
    review = review || {};
    self.vm = vm;
    self.Id = ko.observable(review.Id || 0);

    // More properties if needed
}

// Add an editItem prototype to each Review
Review.prototype.editItem = function(review) {
    // The bound item is passed in with the click binding
    window.location = "/item/edit/" + review.Id();

    // Or without using the item passed
    // window.location = "/item/edit/" + this.Id();

    // Or using the editItem function on the view model
    // this.editItem = this.vm.editItem(review);
};


function ReviewViewModel() {
    var self = this;
    self.myListData = ko.observableArray([]);

    // Add some sample data to the observable array
    var myListData = [];
    myListData.push(new Review({ Id: 1}, self));
    myListData.push(new Review({ Id: 2}, self));
    myListData.push(new Review({ Id: 3}, self));
    myListData.push(new Review({ Id: 4}, self));

    self.myListData(myListData);

    // If you would rather have the editItem function on the view model
    self.editItem = function(review) {
        window.location = "/item/edit/" + review.Id();
    };
}

// Markup
<button data-bind="click: editItem">View</button>