knockoutjs get element id through click event
Asked Answered
M

2

22

I'm using knockoutjs and I currently have something in my view that looks like this:

<img id="myTab1" data-bind="click: pressedTab.bind($data, '#myTab1')" src="images/image1.png"></img>

This allows me to get the element ID in my view model:

pressedTab = function(tab){
    console.log("Element ID: " + tab);
}

This writes:

Element ID: #myTab1

However, it's too repetitive to send the name of the img id in the click event. Is there a way to send the img id without explicitly re-writing it?

Mishamishaan answered 22/6, 2012 at 14:20 Comment(1)
Below link works for me with knockout binding #31514189Freefloating
V
57

You actually can get access to the event object via a KO click handler.

<button id="somebutton" data-bind="click: log">Click Me </button>

var ViewModel = function() {
    this.log = function(data, event) {
        console.log("you clicked " + event.target.id);
    }
};
ko.applyBindings(new ViewModel());

http://jsfiddle.net/madcapnmckay/e8JPT/

Hope this helps.

Vitellin answered 22/6, 2012 at 16:29 Comment(1)
This will not be safe if there is icon on button something like this, <button id="somebutton" data-bind="click: log"><span class='fa fa-user'></span>Click Me </button>Sewn
C
13

The answer of madcapnmckay is not completely correct. You can better use currentTarget: it will return the original bound element instead of a child element, when i.e. you have a div with nested elements in it.

See this question

Update

As @Ryan mentioned - event.currentTarget is not available for IE8. For <= IE8 support you can use:

var target = (event.currentTarget) ? event.currentTarget : event.srcElement;
Churchman answered 31/12, 2012 at 1:16 Comment(2)
I agree. vm.yourFn = function (data, event) { var $target = $(event.currentTarget) ... works great.Pinnace
Please note that if you need to support IE < 9, currentTarget is not available for those versions.Karonkaross

© 2022 - 2024 — McMap. All rights reserved.