What's Wrong With My Event Handler?
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 = {
Solution 1:
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")) };
Solution 2:
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() 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/
Solution 3:
You could just use:
$('#bind')
.data('label', 'underscore')
.click(function() {
alert('clicked: ' + $(this).data('label'));
});
Post a Comment for "What's Wrong With My Event Handler?"