What's wrong with my event handler?

十年热恋 提交于 2019-12-23 18:27:41

问题


Let's say i was attaching an event handler of jquery click event to one of the function of my objects. But why it returns 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 ?

回答1:


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/




回答2:


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")) };



回答3:


You could just use:

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


来源:https://stackoverflow.com/questions/6804622/whats-wrong-with-my-event-handler

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!