Get viewmodel item for a html element - again!

584 views
Skip to first unread message

nevf

unread,
Jun 30, 2011, 7:59:59 PM6/30/11
to knock...@googlegroups.com
Given a KO template item such as:

<button id='btn1' data-bind='text: image'  />

I want to find out the view model item (data binding) that a dom element is associated with. In the case what view model key is associated with the button whose id=='btn1'. Note that in this specific case <button> is in a array of items. Likewise I want to do this for <input data-bind's> 

ex. 

{{each(i, item) common_items.text_images}}
    <button id='btn1' data-bind='text: image'  />
  ...
{{/each}}

    var viewModel = {
        common_items: {
            text_images: new ko.observableArray([]),
        },
        ...
    }

I've tried using elem.tmplItem() but that accesses the viewModel not the elements binding.

This continues on from my earlier posts:
https://groups.google.com/d/topic/knockoutjs/vPUdMlec4V8/discussion

rpn

unread,
Jul 1, 2011, 12:02:54 AM7/1/11
to knock...@googlegroups.com
I don't think that there is a way to get that information without some extra clues.  You could write a custom binding handler to store the information with the DOM node.  

For example, it might look like:

ko.bindingHandlers.domData {
    initfunction(elementvalueAccessor{
        $(element).data("ko_data"valueAccessor());  
    }
};


You would use it like:

<button id='btn1' data-bind='text: image, domData: image'  />

Then, you would retrieve it like:

var myData $("#btn1").data("ko_data");

If you are not using jQuery, then you could use Knockout's own DOM data utilities like:

ko.utils.domData.set(element,"ko_data"valueAccessor());

and

ko.utils.domData.get($("#name1")[0]"ko_data")

You could certainly use a different key than "ko_data" or even pass it in on the binding ( domData: { myKey: image } ).

If you wanted to write a wrapper binding, just to make the syntax a little cleaner in the binding, then you could write one like (call it whatever you like):

ko.bindingHandlers.textPlusData {
    initfunction(elementvalueAccessor{
        $(element).data("ko_data"valueAccessor());  
    },
    updateko.bindingHandlers.text.update
};


Then, you could just use it like:

<button id='btn1' data-bind='textPlusData: image'  />
 


nevf

unread,
Jul 1, 2011, 4:34:00 AM7/1/11
to knock...@googlegroups.com
Thanks a lot Ryan. I've actually found a better & simpler solution to my specific issue, however I'm sure this will be useful at some point. 

I'm a little surprised this capability isn't in KO. I assumed that KO must know about DOM elements and their associated bindings, so there would be some way of getting this info from KO.

Reply all
Reply to author
Forward
0 new messages