我的事件处理程序有什么问题? [英] What's wrong with my event handler?
问题描述
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屋!