Understand JQuery's event binding feature and event namespace mechanism, and write better and more flexible event processing code

Source: Internet
Author: User

Understand JQuery's event binding feature and event namespace mechanism, and write better and more flexible event processing code

Bind () and unbind () in JQuery provide the event binding and cancellation mechanisms, which can bind events supported by html by default and custom events. JQuery supports custom events, which obviously brings great flexibility to programming. Next, let's take a look at some of the features of jquery event processing.


1. Events in JQuery can be bound repeatedly without overwriting.

$("#button1").bind("click",function(){alert("func1");});$("#button1").bind("click",function(){alert("func2");});

When you click button1, both event handlers are triggered. Maybe you will say that the above is bound to different anonymous functions, occupying different memory space. This is true, but even the same processing function still has the issue of repeated binding. When button1 is clicked, the following event processing function is also called twice.

$("#button1").bind("click",sameFunc);$("#button1").bind("click",sameFunc);function sameFunc(){alert("func");}

In most cases, the event processing function only needs to be bound once. Therefore, you must pay attention to the repeated binding of JQuery events. It is not a good practice to execute events multiple times even if there are no bugs.



2. bind multiple events and processing functions at a time.

If you need to register the same handler for multiple events, you can use the following code to simplify the process (the event names are separated by spaces ):

$("#button1").bind("mousedown mouseup",function(){console.log(11);});

If the processing functions of each event are different, you can use the following method (json object ):

$("#button1").bind({"mousedown":function(){console.log("mousedown");},"mouseup":function(){console.log("mouseup");}});



3. Pass the event object and custom parameters.

In general, when using jquery, we seldom need event objects and do not need to pass custom parameters to event processing functions. But if we really need to do this, JQuery also supports it.

$("#button1").bind("click", {name:"aty"}, function(eventObject){      alert("params=" + eventObject.data.name);  });
EventObject is similar to the event object in IE and FF. It can be used to obtain more detailed information when an event occurs. If we specify a custom parameter, JQuery places it in the data Attribute of the event object, that is, the passed parameter value can be obtained through eventObject. data.


4. Events are canceled in three forms.

Unbind is used to cancel the previously bound event handler function. In general, there are three forms: cancel all events, cancel some types of events, and cancel an event handler function of a certain type.

Assume that the click, mouseup, and mousedown events are bound to button1, And the click event is bound to two processing functions.

$("#button1").bind("click",function(eventObj){      console.log("click1");  }); $("#button1").bind("click",function(eventObj){      console.log("click2");  }); $("#button1").bind("mouseup",function(eventObj){      console.log("mouseup");  }); $("#button1").bind("mousedown",function(eventObj){      console.log("mousedown");  });
$ ("# Button1"). unbind (): cancel all bound event handler functions on button1.

$ ("# Button1"). unbind ("click"): only cancel the event handler function of the click type bound to button1.

These two forms are well understood and are also the most common programming practices. In the above Code, we have registered two click Event Handlers. What should we do if we want to cancel 2nd click event handlers and retain 1st? We registered anonymous functions, so there is no way to implement them. The following code is incorrect and cannot achieve the expected results.

$("#button1").bind("click",function(eventObj){      console.log("click1");  }); $("#button1").bind("click",function(eventObj){      console.log("click2");  }); // try to cancel function2$("#button1").unbind("click",function(eventObj){      console.log("click2");  }); 

Although bind and unbind use the same anonymous functions, these two functions are not the same javascript Object because they occupy different memory space. You may have come up with the idea that if bind and unbind use the same function, will it achieve the goal? Indeed, the following code is correct.

$("#button1").bind("click",func1); $("#button1").bind("click",func2); // try to cancel function2$("#button1").unbind("click",func2); function func1(){console.log("click1");  }function func2(){console.log("click2");  }
This is the third form of unbind. We can see that this method is very bad, because this method does not allow anonymous functions, we have to expose global functions (at least unbind is required to be visible ). JQuery provides the event namespace mechanism. I personally think it is to solve this problem.


5. Event namespace.

As mentioned above, the event namespace is used to solve the problems encountered in the third form of unbind. The following is an explanation of JQuery's official API documentation:

Instead of maintaining references to handlers in order to unbind them, we can namespace the events and use this capability to narrow the scope of our unbinding actions.

The so-called event namespace is to add an alias after the event type with the dot syntax to reference the event, such as "click. a ", where" a "is the alias of the click current event type, that is, the event namespace. Because the point number is used to define the namespace, if we use a Custom Event, the event name must not contain the point number. Otherwise, unexpected problems may occur. There is no need to try this problem. special characters are not needed if they are not needed. Otherwise, you may find trouble for yourself.

$("#button1").bind("click.a",function(eventObj){      console.log("click1");  }); $("#button1").bind("click.b",function(eventObj){      console.log("click2");  }); // success to cancel function2$("#button1").unbind("click.a"); 
As you can see, namespace can be used to cancel an event handler function of an event type in a more elegant way. It is worth mentioning that the namespace used does not conflict with the unbind, and the above three forms of unbind can still be used normally. $ ("# Button1 "). unbind () can still cancel all events on button1, $ ("# button1 "). unbind ("click") can still cancel all click events. This Compatibility Design is great.


One more benefit to using a namespace is the ability to cancel events by namespace.

// Two namespaces a and B $ ("# button1 "). bind ("click. a ", function (eventObj) {console. log ("click1") ;}); $ ("# button1 "). bind ("click. B ", function (eventObj) {console. log ("click2") ;}); $ ("# button1 "). bind ("mouseup. a ", function (eventObj) {console. log ("mouseup") ;}); $ ("# button1 "). bind ("mousedown. a ", function (eventObj) {console. log ("mousedown ");});
In this Code, we use two namespaces a and B. If I only want to retain 2nd click event handlers, delete all the remaining ones. We can achieve this in two ways:

Method 1:

$("#button1").unbind("click.a");$("#button1").unbind("mouseup");$("#button1").unbind("mousedown");

Method 2:

$("#button1").unbind(".a");


Obviously, method 2 is simpler and more skillful. Although the code is less understandable, you can understand it as long as you are familiar with JQuery. There are only two types of project code that you can't understand: no one else can, no code can be written, or no code can be written by yourself. If you are not familiar with a language, how can you use it to write code? Therefore, code quality and development efficiency are closely related to individual skill levels and team levels.


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.