Let’s say I was attaching an event handler of jQuery click event to one of the function of my objects. But why does it return undefined on my properties?
var buttonView = {
label : 'underscore',
onClick : function(){ alert('clicked: ' + this.label); },
};
$('#bind').bind('click', buttonView.onClick); //clicked: undefined --> why is it undefined ?
You’re passing the function referenced by
buttonView.onClick, but it’s association withbuttonViewis not retained.To retain the reference via
this, you can use thejQuery.proxy()[docs] method.Now
thisin theonClickfunction will refer to yourbuttonViewobject.Live example: http://jsfiddle.net/K72qs/
Or simply make an explicit reference to
buttonViewin theonClickfunction:Live example: http://jsfiddle.net/K72qs/1/