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?
Your syntax and use of $container with jquery and the second argument of ‘.person’ is unfamiliar to me, but in your click handler, isn’t
thisthe element that was clicked? Couldn’t you pass that to your showPerson method also?I don’t know of a way off the top of my head to get the elements that an observable is bound to, but it could be several different elements. You could have a text box for ‘name’, display the name in a span, use it in a computed, have subscribers, and use name().length in a calculation in another binding for instance.
That said, if you use the debug version of knockout, you can see that your observables have a
_subscriptionsproperty that might have what you’re looking for. The minified version is some single character I think.