Is it at all possible to get the corresponding element (or elements) that a data (model) instance was bound to?
For example, I have an array of 'Person' objects stores in a ViewModel property.
I bind the ViewModel to the view which renders it, eg:
<div class="people" data-bind="template: { foreach: people }"> <a href="#" class="person" data-bind="text: name"></a> </div>
I then bind some event handlers via jQuery:
$container.on('click', '.person', function(e){ e.preventDefault(); self.showPerson( ko.dataFor(this) ); });
In my showPerson
method I would save a reference to the model. I /could/ also a save a reference to the element, but I don't want to if I don't have to.
self.showPerson = function(person) { // can i get the corresponding element from the 'person' model? };
Anyone got any ideas?
You can simply create a custom binding
// data-bind="element: observable" // sets observable to element .. ko.bindingHandlers.element = { init: function(element, valueAccessor) { var target = valueAccessor(); target(element); } };
In your view model, create a 'field' to store the element:
person.el = ko.observable(null);
Then in your html template ..
<div data-bind="element: el"> .... </div>
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