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?
so I can use the same button
in any foreach
binding?
Clarification:
I know how to do that if I put remove
into the view model. 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. 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.
<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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With