Read the core method for adding events on jQuery's 11th. _ jquery-js tutorial

Source: Internet
Author: User
In the previous article, we mentioned that many bindclick interfaces provided by adding events in jQuery to client programmers, but the core implementation method is jQuery. event. add. This article takes a look at its source code. The add definition is as follows (Omitted in most cases)

The Code is as follows:


Add: function (elem, types, handler, data ){
If (elem. nodeType = 3 | elem. nodeType = 8 ){
Return;
}
...
}


Four parameters, elem, types, handler, and data, are defined as HTMLElement, event type (such as click), event response function, and data. In addition, types can separate multiple events ("mouseover mouseout") with spaces "). Handler is sometimes an object (when live is implemented ). Data will end with the extended event object, that is, the attribute of the event. Event will be obtained in handler as the first parameter, so that data can be obtained in handler.
The following details

The Code is as follows:


If (elem. nodeType = 3 | elem. nodeType = 8 ){
Return;
}


The text and comment nodes return directly.

The Code is as follows:


If (handler = false ){
Handler = returnFalse;
} Else if (! Handler ){
// Fixes bug #7229. Fix recommended by jdalton
Return;
}


When handler is set to false, handler is assigned a value of returnFalse and a value of returnFalse as a function, as shown below:

The Code is as follows:


Function returnFalse (){
Return false;
}


JQuery blocks the default behavior of elements by setting handler to false and stops event bubbling. This should be viewed in conjunction with jQuery. event. handle.

The Code is as follows:


Var handleObjIn, handleObj;
If (handler. handler ){
HandleObjIn = handler;
Handler = handleObjIn. handler;
}
// Make sure that the function being executed has a unique ID
If (! Handler. guid ){
Handler. guid = jQuery. guid ++;
}


Define the handleObjIn and handleObj variables.
Handler is literally an Event Response (callback) function, but handler. handler appears here, which is strange. When Will handler be passed in as a JS object?
Most of the time, the Function type is passed. If you look at the jQuery. event. add call in the source code, you can find that jQuery will pass the Object type when implementing live. As follows:

The Code is as follows:


Add: function (handleObj ){
JQuery. event. add (this,
LiveConvert (handleObj. origType, handleObj. selector ),
JQuery. extend ({}, handleObj, {handler: liveHandler, guid: handleObj. handler. guid }));
},


In this case, handleObjIn is assigned as the passed JS object. The real handler is handleObjIn. handler. This is a bit difficult to understand.

The Code is as follows:


// Make sure that the function being executed has a unique ID
If (! Handler. guid ){
Handler. guid = jQuery. guid ++;
}


The passed handler parameter adds a property guid as a number starting from 1. When you use jQuery to add events, the property guid is added to the Event Response Function by default. This guid is used to delete events.

The Code is as follows:


// Init the element's event structure
Var elemData = jQuery. _ data (elem );


Obtain elemData first. Here we use the jQuery. _ data mentioned above. The first time you add an event for HTMLElement, elemData is an empty object ({}).

The Code is as follows:


// If no elemData is found then we must be trying to bind to one of
// Banned noData elements
If (! ElemData ){
Return;
}


If elemData does not exist, return directly.

The Code is as follows:


Var events = elemData. events,
EventHandle = elemData. handle;


Define events and eventHandle. At the same time, both variables are undefined.

The Code is as follows:


If (! Events ){
ElemData. events = {};
}
If (! EventHandle ){
ElemData. handle = eventHandle = function (e ){
// Discard the second event of a jQuery. event. trigger () and
// When an event is called after a page has unloaded
Return typeof jQuery! = "Undefined "&&(! E | jQuery. event. triggered! = E. type )?
JQuery. event. handle. apply (eventHandle. elem, arguments ):
Undefined;
};
}


Assign values to elemData. events and elemData. handle.

The Code is as follows:


// Add elem as a property of the handle function
// This is to prevent a memory leak with non-native events in IE.
EventHandle. elem = elem;


Temporarily store elem to eventHandle. When you delete event registration, it is set to null to avoid Memory leakage in Some browsers.

The Code is as follows:


// Handle multiple events separated by a space
// JQuery (...). bind ("mouseover mouseout", fn );
Types = types. split ("");


Converts a string into an array with spaces as the delimiter. This statement allows you to add multiple events at a time. The handler of multiple events is the same.
Followed by a while loop

The Code is as follows:


While (type = types [I ++]) {
HandleObj = handleObjIn?
JQuery. extend ({}, handleObjIn ):
{Handler: handler, data: data };
...
}


Loop array, which is processed in sequence as follows
, Get handleObj
To process the event namespace, Which is differentiated by the period. If type is a bit numbered, it has a namespace. Otherwise, no
To add the type and guid attribute to handlerObj. Used in subsequent event Deletion
, Get handlers, special. In most cases, addEventListener/attachEvent is used to add events. The special variable shows that special events such as ready, beforeunload, and live events are specially handled. Ready calls jQuery. bindReady, while jQuery. bindReady calls addEventListener/attachEvent internally. Beforeunload is added using window. onbeforeunload. Live is an event proxy, and its processing is also special.
And add handleObj to the array handles.
The last sentence of jQuery. event. add solves Memory leakage in IE.

The Code is as follows:


// Nullify elem to prevent memory leaks in IE
Elem = null;


I made a diagram of the data structure of jQuery event management. As follows:

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.