Design of jquery class Library

Source: Internet
Author: User

So far, jquery is the most active and most user front-end Class library in JS community, which has the features of chain operation, compatibility, array-based operation, powerful plug-in mechanism and so on, as well as many front-end beginners. But how it was implemented in the interior has been attracting me. So the last three months to read the jquery1.7 version of the design, the reason for choosing this version is because sizzle introduced a compiler function after 1.8, the code changes relatively large.

1. Overall design

In this paper, the jquery1.7 version of the reading study, the entire jquery source is divided into 11 modules, these modules interdependent, forming a simple, powerful JS class library. jquery is a DOM-based class library, so the implementation of the Sizzle selector engine is particularly important. For the implementation of the Sizzle selector engine, previously done first-off analysis, see: Sizzle selector engine introduction. The following is a simple introduction to data storage, event handling, exception request Ajax, animation, and so on.

(function(window, undefined) {varJQuery =function(Selector, context) {return NewJQuery.fn.init (Selector, context, rootjquery); } Jquery.fn=function() {        //Prototype Object        ...    } //Tool Methods    //Asynchronous Queues    //Queues Queue    //Browser Test support    //Property Manipulation    //Event System    //DOM traversal and manipulation, style manipulation    //Ajax Requests    //Animation}) (window)
2. Data storage

In actual project development, it is often necessary to attach some information to a DOM node, so it is important to manage the relationship between the DOM node and the attached data. Obviously, there are two ways to solve this problem: 1) directly attached to the DOM node, 2) The DOM node is associated with an ID, additional data. There are pros and cons to both approaches: the benefit of Method 1 is that DOM nodes, additional data together, are easy to maintain, and the benefit of Method 2 is that you can avoid mutual reliance and avoid memory leaks.

var arr = []; function CreateNode () {     return document.createelement (' div ');} function savenodes () {    for (var i=0; i<100;i++) {        Arr.push (CreateNode ());}    }  //  The above 100 nodes nodes are rendered to the page and then removed from the page, so because arr refers to 100 nodes nodes, these nodes cannot be reclaimed by the garbage collection mechanism, causing a memory leak issue. 

3. Asynchronous deferred

The implementation of the asynchronous in jquery, in general, follows the PROMISE/A specification, why is it roughly?

    1. Then return: the then method does not return a new asynchronous object, which does not conform to the then requirement in the PROMISE/A specification. This has been modified since jQuery2.0
    2. Result processing: jquery does not have an abnormal capture of results when processing results
    3. Number of parameters: Resolve can have multiple parameters in jquery, while Promise/a's resolve can have only one

Internal implementation of the tortuous abstract, the code is obscure, mainly through the "Once", "memory" two parameters to control: "Once" determines that the asynchronous callback function can only be executed once; "Memory" determines that the function has the memory kinetic energy, that is, after the asynchronous event completes, then binds the callback function, The callback function executes immediately.

4. Event handling

jquery internal events are powerful, in addition to the ability to handle DOM events, you can customize events, trigger events (DOM events, custom events), define namespaces for events, and more. And another bright spot inside jquery is to minimize the dependency between DOM and listener events by using the data storage module, which avoids the memory leaks caused by the mutual dependence of Dom and JS objects. The data structure of the cache module is as follows:

$ ('. a '). On (' click ',function() {});//results is as fellow:$.cache = {    1: {events: {click: [//Click.delegatecount: Record the number of agent events, and the proxy callback function is placed in front of the array{data: ..., GUID: ..., selector: ..., Handler:function() {},//Handler.guid = 1 for locating and removing listener functions                    ....                } ]}, handle:function() {......}//Main Listener function    }}
4.1 Event Bindings:

When the event is bound, the call chain for the internal method is: Bind/delegate/live/one ()--->.on ()->$.event.add ()->$.data ()/addeventlistener/ Attachevent (). In fact, in the case of a DOM element, all events correspond to a main listener function ($._data (elem). Handle), and the corresponding type of listener function is triggered through the main listener function through the event distribution function ($.event.dispatch).

$ ('. a '). On (' click '), FN1); $ ('. a '). On (' Blur ', FN2); $ ('. a '). On (' Focus ', fn3);//in fact, Dom elements (. A) are not directly associated with FN1, FN2, FN3, but event distribution through dispatch//The pseudo-code can be represented as follows:$ ('. a '). On (' click Blur Focus '), dispatch);functionDispatch (type) {varfn; if(Type = = ' click ') {fn=fn1; } Else if(type= = = ' Blur ') {fn=fn2; } Else if(Type = = ' Focus ') {fn=Fn3; }    returnfn;}
4.2 Event Removal

When removing an event, the call chain for the internal method is: Unbind/delagate/die ()--->.off ()->$.event.remove ()->$._data ()/removeeventlistener/ DetachEvent (). The event is removed, that is, the corresponding event object is removed from the Datastore object $.cache, and the entire data cache object is removed when event object events is empty.

4.3 event manual trigger

In jquery, you can manually trigger DOM events or custom events. The call chain for the internal method is:. Trigger/triggerhandler (), $.event.trigger (), $.event.dispatch (main listener function), the listener function for the event.

Another issue that needs attention is how do events bubble up? The method is very simple, that is, according to the structure of the DOM to query the ancestor elements of the element, all the way to the Window object, which constitutes the element's bubbling path, and then trigger the corresponding event of the element on this path. This is also a key part of jquery's ability to simulate event bubbling with focus, blur, change, and submit.

// find the Bubbling path var eventpath = [];  for (; cur; cur = cur.parentnode) {    Eventpath.push ([cur, type]);} // the listener function on the execution path  for () {    = eventpath[i][0];     =  eventpath[i][1];     = $._data (cur, "events") [type];    Hanle.apply (cur);}

5. Asynchronous Request Ajax

The asynchronous request is that jquery can be divided into three parts: the core implementation, the convenient method, the Ajax global event. The module relies on the asynchronous programming module provided by the deferred module to facilitate the registration of callback functions, for example:

$ (URL, options). Then (SUCCESSFN, FAILFN);

The implementation of core methods mainly includes the following:

    1. Parameter settings: In all jquery APIs, the. ajax parameter type should be for many, inside the parameters to see people cover sportive. However, the final URL, type, DataType, data, and especially DataType settings for the results should be very large, so there is a lot of code to deal with this step.
    2. Pre-filter function processing: Mainly for JSON, JSONP, script three types of data processing, before the request is sent to filter processing
    3. Request issued: There are two ways in which the request is issued, depending on the XMLHttpRequest and script tags. If the browser allows cross-domain, it is sufficient to use only XMLHttpRequest.
    4. Execution of the callback function: There are many kinds of callback functions here, before the request is sent, the data is accepted, the data is accepted and so on.

6. Animation parsing

In jquery, animations show, Hide, FadeIn, fadeout, and so on are called animation methods, which means that animation is the most basic entry function. You can see that the entry function includes three procedures: parameter configuration, animation function generation, animation function execution. The following details are covered below:

    1. Parameter configuration: There are three main parameters, duration is the execution time of animation, and easing is the speed of each frame change, there are only two frame change functions in jquery: Linear (linear) change, cosine change (swing), only $ can be modified with other change functions. Fx.easing object; Complete is the callback function that needs to be executed after the animation is completed.
    2. Generating an animated function Doanimation:jquery generates a $.fx object for each style that is used to animate the effect. By default, a frame animation is performed every 13ms, and then the style of the page is updated.
    3. Animation execution: If the animation does not need to be queued, the animation function doanimation is executed immediately after the animation function is generated, instead, the doanimation is queued in queue queues. Once all the animations have been completed, you can execute the callback function complete.

Of course, jquery's internal implementation is complex, taking into account function pauses, style temporary modifications (when modifying the width/height of an inline element, it temporarily modifies its display to Inline-block), empties the animation queue, and so on.

Resources

Https://developer.chrome.com/devtools/docs/demos/memory/example6

Design of jquery class Library

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.