Knockout.js get dom object associated with data

Event handlers like click get passed two arguments. That is

  1. 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).

  2. 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”):

    getDomObject = function(item, event) {
        var $this = $(event.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/

var Item = function(color) {
  this.color = String(color);
  this.setTextColor = function(item, event) {
    $(event.target).css('background', color);
  };
};

ko.applyBindings(new function() {
  this.Items = ko.observableArray([
    new Item('red'),
    new Item('blue'),
    new Item('green')
  ]);
}());
li {
  padding: 2px 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/2.0.0/knockout-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<ul data-bind="foreach: Items">
  <li>
    <button data-bind="click: setTextColor, text: 'Color: ' + color"></button>
  </li>
</ul>

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)