Js uses function binding technology to change the scope of the event handler

Source: Internet
Author: User

The first and most common is to register an event directly in the html Tag by specifying the HTML attribute with the same name as the event handler. The Code is as follows: Copy codeThe Code is as follows: function eventHandler (){
Alert ("the current scope is the input element itself ");
}
<Input type = "button" value = "click I" onclick = "eventHandler (this)"/>

The second method is to assign a function to an event handler attribute. In this way, the element object is obtained first. The general code is as follows:Copy codeThe Code is as follows: <input id = "myEventHandlerScope" type = "button" value = "Click me"/>
<Script type = "text/javascript">
Function eventHandler (){
Alert ("the current scope is the input element itself ");
}
Var mybtn = document. getElementById ("myEventHandlerScope ");
Mybtn. onclick = eventHandler;
</Script>

The third method is the DOM2-level event processing methods addEventListener and removeEventListener. The corresponding methods for IE browsers are attachEvent and detachEvent. The code for registering an event is as follows:Copy codeThe Code is as follows: <input id = "myEventHandlerScope" type = "button" value = "Click me"/>
<Script type = "text/javascript">
// Define a method for registering an event
Function addHandler (obj, type, handler ){
If (obj. addEventListener ){
Obj. addEventListener (type, handler, false );
} Else if (obj. attachEvent ){
Obj. attachEvent ("on" + type, handler );
} Else {
Obj ["on" + type] = handler;
}
}
Function eventHandler (){
Alert ("the current scope is the input element itself ");
}
Var mybtn = document. getElementById ("myEventHandlerScope ");
AddHandler (mybtn, 'click', eventHandler); // registers an event for the object
</Script>


One disadvantage of registering a click event handler for the input element in the preceding three methods is that the handler's scope (this) is always in the input object. In object-oriented programming, You need to explicitly specify this under a specific scope. To change the scope of this, a binding function technology of js is used.
The so-called "binding function" is to create a function, which can call another function with specified parameters in a specific environment. It can be used well with the event handler, so that the function can be passed as a variable while maintaining the function scope (also the execution environment of this ). The binding function is defined in the following code:

Copy codeThe Code is as follows: function bind (fn, scope ){
Return fn. apply (scope | this, arguments );
}

This binding function accepts two parameters. The first is the function to be executed, the second is the specific execution environment, and returns a function that calls a given function in a given scope, and pass all parameters together. By using the binding function technology and the DOM2-level event handler, you can register an event handler function executed in a specific scope for the element. The specific processing method is as follows:
The following code first modifies the previously defined registration event:Copy codeThe Code is as follows: function addHandler (obj, type, handler, scope ){
Function fn (event ){
Var evt = event? Event: window. event;
Evt.tar get = event.tar get | event. srcElement;
Return handler. apply (scope | this, arguments );
}
Obj. eventHash = obj. eventHash | |{}; // defines a hash object for the object that needs to register the event handler, and stores the event handler and scope in the queue of this event type.
(Obj. eventHash [type] = obj. eventHash [type] | []). push ({"name": type, "handler": handler, "fn": fn, "scope": scope });
If (obj. addEventListener ){
Obj. addEventListener (type, fn, false );
} Else if (obj. attachEvent ){
Obj. attachEvent ("on" + type, fn );
} Else {
Obj ["on" + type] = fn;
}
}

The modified event registration method enables the event handler of the element to be executed in the specified environment.Copy codeThe Code is as follows: <input id = "myEventHandlerScope" type = "button" value = "Click me"/>
<Script type = "text/javascript">
Function eventHandler (){
This;
Alert ("the current scope is the window element itself ");
}
Var mybtn = document. getElementById ("myEventHandlerScope ");
AddHandler (mybtn, 'click', eventHandler, window );
</Script>

Execute the above Code, and the processing program eventHandler's this scope is under the window object.

As described above, registering an event by binding a function creates an event hash object for the element object to save the event handler, this hash object is always around when an element is removed from the event handler. Based on this, it can accurately remove the corresponding event handler. The code for removing the event handler is as follows:Copy codeThe Code is as follows: function removeHandler (obj, type, handler, scope ){
Obj. eventHash = obj. eventHash | | {};
Var evtList = obj. eventHash [type] | [], len = evtList. length;
If (len> 0 ){
For (; len --;){
Var curEvtObj = evtList [len];
If (curEvtObj. name = type & curEvtObj. handler = handler & curEvtObj. scope = scope ){
If (obj. removeEventListener ){
Obj. removeEventListener (type, curEvtObj. fn, false );
} Else if (obj. detachEvent ){
Obj. detachEvent ("on" + type, curEvtObj. fn );
} Else {
Obj ["on" + type] = null;
}
EvtList. splice (len, 1 );
Break;
}
}
}
}

This section describes how to use the function binding technology to register an event handler for a specific execution environment. Similarly, function binding allows the callback function to be executed in a given execution environment.

The copyright of this article is shared by the author and the blog Park. You are welcome to repost this article. However, you must retain this statement without the author's consent and provide a clear link to the original article on the article page. Otherwise, you will be held legally liable.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.