[英]Knockout.js: access parent collection in data-bind event
Let's say I have a 比方说我有一个
<button type="button" data-bind="click: actions.remove">×</button>
and a handler 和一个处理程序
var actions = {
remove: function(item) {
?array?.remove(item); // ?array? is a containing array, accessed somehow
}
}
How do I find ?array?
我如何找到?array?
so I can use the same button
in any foreach
binding? 所以我可以在任何foreach
绑定中使用相同的button
?
Clarification: 澄清:
I know how to do that if I put remove
into the view model. 如果我将remove
放入视图模型,我知道如何做到这一点。 However the view model contains hierarchical arrays and I do not really want to go through it all just to get methods in the right places. 然而,视图模型包含分层数组,我真的不想通过它只是为了让方法在正确的位置。 View model is also updated from server occasionally with the help of ko.mapping
, but that does not add any methods to the new data. 在ko.mapping
的帮助下偶尔也会从服务器更新视图模型,但这不会为新数据添加任何方法。 That is why I implemented the handlers separately. 这就是我单独实现处理程序的原因。
You try something like this. 你尝试这样的事情。
<div data-bind="foreach: someArray">
<button type="button" data-bind="click: $parent.actions.remove">x</button>
</div>
//Inside your viewmodel.
var self = this;
self.someArray = ko.observableArray();
self.actions = {
remove: function() {
self.someArray.remove(this); // ?array? is a containing array, accessed somehow
}
}
edit: Sorry, I misread what you meant. 编辑:对不起,我误解了你的意思。 You can try something like this to make it work for any foreach binding. 您可以尝试这样的方法,使其适用于任何foreach绑定。
<div data-bind="foreach: someArray">
<button type="button" data-bind="click: function() {$parent.actions.remove($parent.someArray(), $data}">x</button>
</div>
//Inside your viewmodel.
var self = this;
self.someArray = ko.observableArray();
self.actions = {
remove: function(arr, item) {
arr.remove(item); // ?array? is a containing array, accessed somehow
}
}
It is not currently possible. 目前还不可能。
I raised a new knockout issue for that (currently open): 我为此提出了一个新的淘汰赛问题(目前已公开):
Allow access to the current array through the binding context . 允许通过绑定上下文访问当前数组 。
Also relevant: Support for $last in foreach . 同样相关: 在foreach中支持$ last 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.