I'm working with knockout.js to build dynamic lists and I'm trying to figure out how I can get the DOM object associated with an object in my observable array. Specifically I want to get the jQuery for a row.
Example:
<ul data-bind="foreach: Item">
<li data-bind="events: {click: getDomObject}, text: 'text: ' + text">
</li>
</ul>
in the getDomObject
function, I would like to be able to get the specific <li></li>
DOM object so that I can do some jQuery manipulation with it.
I've thought about adding an id
member to the Item ViewModel and then add the id as the line item's html id and then select based on that, but I feel that there should be an easier way.
What is the proper way to reference the dynamic HTML generated by knockout.js?
Event handlers like click get passed two arguments. That is
the item that this event belongs to - like the entry of an observable array that you're rendering with the foreach binding ("Item" in your case).
And, an event object, that provides you with more information about the actual event. This object contains the DOM element that got clicked on (key "target"):
Just a note: Don't mix knockout and native jQuery DOM manipulations - if you can achieve the same result with clever knockout bindings, I would recommend going with that.
And here is a simple demo: http://jsfiddle.net/KLK9Z/213/
I had a similar problem. I come up with a solution resembling Backbone.js use of el and $el references.
in your ViewModel:
in html (for example list element):
in bindingHandlers (showing all possible arguments to init):
For example, then you can use $el like:
Hope this helps!
The $(event.target) solution is good if it is related to an already occurring event in which the item's DOM element is at target. But sometimes you don't have the targeted item because there is no event (for example - you want to scroll a list to an item that was not gestured by the user).
In such case you can give the item's DOM element id attribute a unique value that contains the item id:
and then getDomObject() looks like:
My solution (valid for "value" binding)
Now you have yourobservable.$el and yourobservable.el which bind to jquery and DOM element.
To add yet a 3rd option, also for cases where you don't have an event to work with (if you have an event, the accepted answer is best/optimized).
Create a custom binding such as:
usage is as follows:
In the above case, $parent is my View Model. I have an observable object which contains a unique ID. Anytime I set that scrollTo() object, the list scrolls to that item.
Note that my code assumes the parent DIV of the LI has the scrollbar (overflow:auto/scroll). You can adjust for your needs, possibly use a class on the parent and use that for your jQuery selector, or to make very flexible you could pass in the selector via your data-bind options... for me, this was enough, as I always use divs for my scrollable sections.