问题
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