Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KnockoutJs: Get the bound element from a model instance

Tags:

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?

like image 423
badsyntax Avatar asked May 25 '12 15:05

badsyntax


1 Answers

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> 
like image 115
hasen Avatar answered Oct 13 '22 11:10

hasen