Corey Ogburn
Corey Ogburn

Reputation: 24717

Know which element was clicked when using source/template binding?

My HTML:

<ul style="padding-left: 0px;" data-template="GallaryTemplate" data-bind="source: Job.Images"></ul>
<script id="GallaryTemplate" type="text/x-kendo-template">
    <li style="display: inline">
        <img data-bind="attr: { src: Path }, click: clickHandler" style="width: 50px; height: 75px;" />
    </li>
</script>

My view model:

{
   "ActiveImage":0,
   "Job":{
      "JobUID":100,
      "PatientFirstName":"Corey",
      "PatientLastName":"Ogburn",
      "PatientGender":1,
      "Images":[
         {
            "ImageUID":1,
            "JobUID":100,
            "Path":"/data/A.png"
         },
         {
            "ImageUID":2,
            "JobUID":100,
            "Path":"/data/B.png"
         },
         {
            "ImageUID":3,
            "JobUID":100,
            "Path":"/data/C.png"
         }
      ]
   },
   clickHandler: function() {...}
}

For my generically named clickHandler, how can I get the index of which image I'm clicking on? Knockout had a $index, what's the Kendo equivalent?

Upvotes: 0

Views: 937

Answers (2)

OnaBai
OnaBai

Reputation: 40887

You get a reference to the data in e.data being e the argument to clickHandler.

Example:

clickHandler: function(e) {
    console.log("data", e.data);
}

Check it here: http://jsfiddle.net/OnaBai/XNcmt/74/

EDIT You might also consider setting the click handler into li element and then you can simplify Lars Höppner proposed solutions as $(e.delegateTarget).index():

Template:

<ul style="padding-left: 0px;" data-template="GallaryTemplate" data-bind="source: Job.Images" id="list"></ul>
<script id="GallaryTemplate" type="text/x-kendo-template">
    <li style="display: inline" data-bind="click: clickHandler">
        <img data-bind="attr: { src: Path }" style="width: 50px; height: 75px;" />
    </li>
</script>

JavaScript click handler:

clickHandler: function(e) {
    alert("li index: " + $(e.delegateTarget).index());
}

See it here: http://jsfiddle.net/OnaBai/XNcmt/75/

Upvotes: 1

Lars H&#246;ppner
Lars H&#246;ppner

Reputation: 18402

As OnaBai said, you can inspect the event passed to the click handler; to get the index, you can take a look at e.target, which is the element the user clicked on, and get the index like this:

clickHandler: function(e) {
    var index = $(e.target).closest("li").index();
}

if you need the index in the array as opposed to the index of the element, you can also do this:

clickHandler: function (e) {
    var index = e.data.parent().indexOf(e.data);
}

(demo)

Upvotes: 1

Related Questions