Γ—

Knockout.js: access to the parent collection in a data binding event

Let's say i have

<button type="button" data-bind="click: actions.remove">Γ—</button> 

and handler

 var actions = { remove: function(item) { ?array?.remove(item); // ?array? is a containing array, accessed somehow } } 

How to find ?array? so that I can use the same button in any foreach binding?

Clarification:
I know how to do this if I put remove in the view model. However, the view model contains hierarchical arrays, and I really don't want to go through all this to get the methods in the right places. The view model is also periodically updated from the server using ko.mapping , but this does not add any methods to the new data. This is why I implemented the handlers separately.

+4
source share
2 answers

This is currently not possible.

I raised a new knockout problem for this (currently open):
Allow access to the current array through the binding context .

Also relevant: $ last support in foreach .

0
source

You will 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 misunderstood what you meant. You can try something like this to make it work for any foreach bindings.

 <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 } } 
+3
source

All Articles