Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
135 views
in Technique[技术] by (71.8m points)

javascript - Access event object in event handler

When i try to attach event handler functions with parameters like :

myhandle.onclick = myfunction(param1,param2);

function myfunction(param1,param2){
}

Now I want to access the event object in my handler function. There is an approach mentioned on the web of sending event object, like:

myhandle.onclick = myfunction(event,param1,param2);

But its giving event object undefined when i test it out.

I know libraries make this stuff easy but I am looking for a native JS option.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

myhandle.onclick = myfunction(param1,param2);

This is a common beginner error at a JavaScript level, and not something that libraries can really fix for you.

You are not assigning myfunction as a click handler, you are calling myfunction, with param1 and param2 as arguments, and assigning the return value of the function to onclick. myfunction doesn't return anything, so you'd be assigning undefined to onclick, which would have no effect..

What you mean is to assign a reference to myfunction itself:

myhandle.onclick= myfunction;

To pass the function some extra arguments you have to make a closure containing their values, which is typically done with an anonymous inline function. It can take care of passing the event on too if you need (though either way you need a backup plan for IE where the event object isn't passed as an argument):

myhandle.onclick= function(event) {
    myfunction(param1, param2, event);
};

In ECMAScript Fifth Edition, which will be the future version of JavaScript, you can write this even more easily:

myhandle.onclick= myfunction.bind(window, param1, param2);

(with window being a dummy value for this which you won't need in this case.)

However, since many of today's browsers do not support Fifth Edition, if you want to use this method you have to provide an implementation for older browsers. Some libraries do include one already; here is another standalone one.

if (!('bind' in Function.prototype)) {
    Function.prototype.bind= function(owner) {
        var that= this;
        var args= Array.prototype.slice.call(arguments, 1);
        return function() {
            return that.apply(owner,
                args.length===0? arguments : arguments.length===0? args :
                args.concat(Array.prototype.slice.call(arguments, 0))
            );
        };
    };
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...