What is the best way to share one function between two different event handlers? I want the same outcome but some situation dependent variables will need to be defined within the function depending on which element was clicked.
I could hack a solution but want to know the best practice for such a scenario. Simple problem must have a simple answer.
EXAMPLE
var onMyEvent = function(e){
if(click triggered from 'a'){
//do that
}
if(click triggered from 'div'){
//do that
}
}
$('a').click(onMyEvent);
$('div').click(onMyEvent);
FIDDLE: http://jsfiddle.net/f6C92/
I guess there’d be several ways to achieve this, such as checking the
evariable for target objects, etc, but for your scenario, the easiest and most readable would be using theis()function, to which you can pass any CSS selector to test if the object of interest matches it.There are those who would argue that the above takes an unnecessary round-trip to jQuery, when you could achieve the same by testing
this.tagName == 'A', but I usually recommend to delegate these things to jQuery as well, for browser compatibility reasons.Another neat way would be to pass the relevant information as event data: