简体   繁体   中英

How do I get access to the event object?

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?

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM