开发者

Event handler returning undefined?

开发者 https://www.devze.com 2023-03-22 07:14 出处:网络
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?

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 ?


In the below onclick handler this points to dom element with id "bind" and it do not have a label property. If you have any custom attribute as label you should use $(this).attr("label") to retreieve it. Try this

 function(){ alert('clicked: ' + $(this).attr("label")) };


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/


You could just use:

 $('#bind')
     .data('label', 'underscore')
     .click(function() {
         alert('clicked: ' + $(this).data('label'));
     });
0

精彩评论

暂无评论...
验证码 换一张
取 消