Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? 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.

like image 232
Andrey Shchekin Avatar asked Oct 21 '22 21:10

Andrey Shchekin


1 Answers

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
}
}
like image 86
T.Ho Avatar answered Nov 02 '22 07:11

T.Ho