Reputation: 11806
I have a JavaScript object that is similar to this:
var MyClass;
MyClass = (function() {
// private
var $elems;
// constructor
function MyClass(selector) {
$elems = $(selector);
$elems.change(myEventHandler(e));
}
// event handler
function myEventHandler(e) {
var isSelected = ($(e.target).attr('checked') == 'checked');
if (isSelected) {
alert('You selected me');
}
}
return MyClass;
})();
I call this class in my html doc like this:
$(function(){
var myClass;
myClass = new MyClass(".MySelector");
});
Which gives me the error:
Uncaught ReferenceError: e is not defined MyClassJsFile.js:17
MyClass MyClassJsFile.js:17
(anonymous function) Step3:36
f.extend._Deferred.e.resolveWith jquery.min.js:16
e.extend.ready jquery.min.js:16
c.addEventListener.B
I thought that I was passing the event object to the event handler in this line of the constructor:
$elems.change(myEventHandler(e));
How do I pass the event correctly in this case?
Upvotes: 0
Views: 111
Reputation: 340055
You can use:
$elems.change(myEventHandler); // or $elems.on('change', myEventHandler) in 1.7+
to just pass the reference to the right handler. As it is you're invoking the handler immediately, and then attempting to bind the (non-existent) return value to the change
handler.
Your check for a selected box is over-complicated, BTW. You should be able to just write:
var isSelected = this.checked;
on the basis that jQuery will set this
to be the actual DOM element that changed, and you can immediately check its boolean checked
property.
Upvotes: 2
Reputation: 44215
You are calling the event handler with an undefined variable. Event handlers are functions, so just pass the function reference without calling it:
$elems.change(myEventHandler);
Upvotes: 4