Skip to content
Advertisement

Event handler returning undefined?

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 ?

Advertisement

Answer

You’re passing the function referenced by buttonView.onClick, but it’s association with buttonView is not retained.

To retain the reference via this, you can use the jQuery.proxy()[docs] method.

$('#bind').bind('click', $.proxy(buttonView,'onClick')); 

Now this in the onClick function will refer to your buttonView object.

Live example: http://jsfiddle.net/K72qs/


Or simply make an explicit reference to buttonView in the onClick function:

onClick : function(){ alert('clicked: ' + buttonView.label); },

Live example: http://jsfiddle.net/K72qs/1/

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement