Thanus
Thanus

Reputation: 451

Knockout js: is it possible to get the bindiing object attached to a HTML element from the HTML tag iteself

If i have a foreach loop in knockoutjs:

<!-- ko foreach: messageModels() -->


                    <li>
                        <a data-bind="click:$parent.startChat.bind(), css: unreadMessagesCount() > 0 ? 'unread' : 'nothing'" style="cursor: pointer" href="#" >
                            <div class="media">
                                <div class="pull-left">
                                    <img class="media-object img-circle" src="assets/images/ici-avatar.jpg">
                                    <!-- ko if: unreadMessagesCount() > 0 -->
                                    <span class="badge badge-red" data-bind="text:unreadMessagesCount()">1</span>
                                    <!-- /ko -->
                                </div>
                                <div class="media-body">
                                    <p class="media-heading"><span  data-bind="text:friend.userName()">Ing. Imrich Kamarel</span> <span class="time" data-bind="text: $parent.convertTime(messages()[messages().length - 1].dateCreated())">12:44</span></p>
                                    <span class="message" data-bind="text:messages()[messages().length - 1].message()">Cras sit amet nibh libero, in gravida nulla. Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis. Fusce condimentum nunc ac nisi vulputate fringilla. Donec lacinia congue felis in faucibus.</span>
                                    <div class="chat-actions">
                                        <span class="mark-unread" title="Mark as unread"><i class="fa fa-circle-o"></i></span>
                                        <span class="archive" title="Archive"><i class="fa fa-times"></i></span>
                                    </div>
                                </div>
                            </div>
                        </a>
                    </li>

                    <!-- /ko -->

if i get a hold of the li tag in the foreachloop using a jquery selector, is it possible to get the object that was bound to it by the foreach loop ?

Upvotes: 0

Views: 31

Answers (1)

user3297291
user3297291

Reputation: 23372

Yes, it's possible using ko.dataFor. For example: ko.dataFor($("li")[0]) returns the viewmodel bound to your first list item.

However, you shouldn't really need ko.dataFor in your production code if you follow knockout's desired architecture patterns... I use ko.dataFor a lot, but mostly for debugging purposes.

You might want to explain why you need to figure out the binding context of an element, because there's probably a better solution to your problem.

Upvotes: 1

Related Questions