Andrey Shchekin
Andrey Shchekin

Reputation: 21609

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.

Upvotes: 5

Views: 2612

Answers (2)

Andrey Shchekin
Andrey Shchekin

Reputation: 21609

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.

Upvotes: 0

T.Ho
T.Ho

Reputation: 1190

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
}
}

Upvotes: 3

Related Questions