Get a thorough understanding of the jquery event principle

Source: Internet
Author: User

jquery provides us with a very rich and useful event API, compared to the browser's own event interface, jquery has the following features:

1. Browser compatibility is handled, user use does not need to consider browser compatibility issues

2. Event data is kept in the internal cache, not on the DOM node

3. The event delegation mechanism provides a very simple way to use event delegates

4. Custom events, not just browser events, can create custom events

5. Accessibility functions, such as namespaces, event data, etc.

Then let's look at how jquery is implemented, first sweep the source structure of the event module:

A total of 900 lines, including a total of 5 parts:

1. Regular and auxiliary functions: the top regular expression and 3 auxiliary functions, which will be said later

2. Event Helper Class: Helper Object for event handling

3. The event writable events object, which is equivalent to the event object in browser events, but the data of the event object is writable, adding some properties of jquery.

4. Compatibility handling: Event compatibility processing logic

5. External API, add to jquery instance object's external API

This code structure is logically divided into 4 layers,

The first layer is the external API, which is the parameter handling of the user call

The second layer is the event helper class, and the user invokes various methods of calling the helper class later

The third layer is the event object, which creates an event object in place of the event object in the browser event during event processing.

The fourth layer is compatibility processing, which is handled for compatibility issues with some events in the browser.

1. We start with the external API, such as:

<div id= ' Div_main ' >    <div id= "div_sub" ></div></div><script>    $ ("# Div_main "). On (" click ",function() {        console.log (1);    });
</script>

We call the on method on the $ ("#div_main") jquery object, so we can register a click event, what is the on method? See external API that part of the code

Onfunction(types, selector, data, FN,/*INTERNAL*/One ) {            varORIGFN, type; //Types can be a map of Types/handlers            if(typeoftypes = = = "Object") {                //(Types-object, selector, data)                if(typeofSelector!== "string") {                    //(types-object, data)data = Data | |selector; Selector=undefined; }                 for(Typeinchtypes) {                     This. On (type, selector, data, Types[type], one); }                return  This; }            if(Data = =NULL&& fn = =NULL) {                //(types, fn)fn =selector; Data= Selector =undefined; } Else if(fn = =NULL) {                if(typeofselector = = = "string") {                    //(types, selector, fn)fn =data; Data=undefined; } Else {                    //(types, data, FN)fn =data; Data=selector; Selector=undefined; }            }            if(fn = = =false) {fn=Returnfalse; } Else if(!fn) {                return  This; }            if(One = = 1) {ORIGFN=fn; FN=function(event) {//Can Use an empty set, since event contains the infojQuery (). Off (event); returnOrigfn.apply ( This, arguments);                }; //Use same GUID so caller can remove using ORIGFNFn.guid = Origfn.guid | | (Origfn.guid = jquery.guid++); }            return  This. each (function() {JQuery.event.add ( This, types, FN, data, selector);        }); },

This code is in fact the user calls the method of the various parameters of the logic of the case, the final root to the JQuery.event.add method, that is, the last call to the event helper class method, first on the method to the user passed the parameters of the judgment, the main may have the following situations:

(1) Passing multiple event methods in JSON, such as:

On ({"Click": Fn1, "blur": Fn2}, "Li", data);
On ({"Click": Fn1, "blur": Fn2},data);

JSON Object Format
if(typeoftypes = = = "Object") {
Selector is not a string is data, then reset data variable, on ({"Click": Fn1, "blur": Fn2},data) if(typeofSelector!== "string") {data = Data | |selector; Selector=undefined; }
Call the on method recursively on each JSON property for(Typeinchtypes) { This. On (type, selector, data, Types[type], one); } return This; }

(2) Three other situations: On ("click", "FN") on ("Click", "Li", fn) on ("click", DATA,FN)

            if(Data = =NULL&& fn = =NULL) {                //similar to ON ("click", fn1), reset variablefn =selector; Data= Selector =undefined; } Else if(fn = =NULL) {                if(typeofselector = = = "string") {                    //Similar on ("click", "Li", fn)fn =data; Data=undefined; } Else {                    //Similar on ("click", Data,fn);fn =data; Data=selector; Selector=undefined; }            }
Shortcut, if the FN parameter is passed false, the method is automatically set to Falseif(fn = = =false) {fn=Returnfalse; } Else if(!fn) { return This; }
            if(One = = 1) {//execute only once, and delete this event object once after execution Origfn=fn; FN=function(event) {//Can Use an empty set, since event contains the infojQuery (). Off (event); returnOrigfn.apply ( This, arguments);                }; //Use same GUID so caller can remove using ORIGFNFn.guid = Origfn.guid | | (Origfn.guid = jquery.guid++); }            return  This. each (function() {//Call JQuery.event.add for each jQuery instance ( This, types, FN, data, selector); });

Then the one method, in fact, is to call the above on method, with a parameter

        function (types, selector, data, fn) {            returnthis. On (types, selector, data, FN, 1);        }, 

Off method, similar to the on method, there are several scenarios for input parameters that ultimately call the Remove method of the event helper class.

Offfunction(types, selector, fn) {varhandleobj, type; if(Types && Types.preventdefault &&types.handleobj) {//(event) dispatched Jquery.eventHandleobj =Types.handleobj; JQuery (Types.delegatetarget). Off (Handleobj.namespace? Handleobj.origtype + "." +HandleObj.namespace:handleObj.origType, Handleobj.selector, Handleobj.handler                ); return  This; }            if(typeoftypes = = = "Object") {                //(Types-object [, selector])                 for(Typeinchtypes) {                     This. Off (type, selector, Types[type]); }                return  This; }            if(Selector = = =false||typeofselector = = = "function") {                //(types [, fn])fn =selector; Selector=undefined; }            if(fn = = =false) {fn=Returnfalse; }            return  This. each (function() {JQuery.event.remove ( This, types, FN, selector);        }); },

The Tigger method is ultimately the Tigger method that invokes the event helper class

        function (type, data) {            returnthis.                 );            });        },

Triggerhandler method, calling the method of the event class

      function (type, data) {            varThis [0];             if (elem) {                returntrue);            }        }

The difference between the Tiggerhandler and Tigger methods is that Triggerhandler executes only the first object in an array of jquery objects and does not perform a bubble and does not perform a browser default event.

Get a thorough understanding of the jquery event principle

Related Article

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.