我的事件处理程序有什么问题? [英] What's wrong with my event handler?

查看:86
本文介绍了我的事件处理程序有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我将jquery click事件的事件处理程序附加到我的对象的某个函数中。但为什么它返回undefined我的属性?

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

$('#bind')。bind('click',buttonView.onClick); //点击:未定义 - >为什么它没有定义?


解决方案

$ c> buttonView.onClick ,但它与 buttonView 不会被保留



要通过这个保留引用,您可以使用 jQuery.proxy() [docs] 方法。 / p>

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

现在这个 onClick 函数将引用您的 buttonView 对象。



直播例如: http://jsfiddle.net/K72qs/






或者只需在 onClick 中明确引用 buttonView code> function:

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

现场示例: http://jsfiddle.net/K72qs/1/


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 ?

解决方案

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/

这篇关于我的事件处理程序有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆