Zepto Source Analysis------Event Chapter

Source: Internet
Author: User

Talk about the source code of Zepto.js. Today I analyze the event, I am lazy, the basic function of the front is not analyzed. Just press the module to write it.

Let's talk briefly about the approximate structure of zepto before analyzing it.

var Zepto = (function{}) ()    //  Event Module    (function($) {}) (Zepto)     // Ajax Modules    (function($) {}) (Zepto)     // form Event    (function($) {}) (Zepto)

The approximate structure is like this; in fact, the function is quite simple, we all know that zepto this framework is designed for mobile development, can be described as short and concise, of course, there are pits AH. Then we are more familiar with the events. Event binding/removal under non-IE is like this

Element.addeventlistener (Type.fn,false/true)
Element.removeeventlistener ()

That would be a good one. Let's talk about bindings first. There's a function inside this guy called the Add function. This is the final binding. Let's analyze and analyze what's in there.

 functionAdd (element, events, FN, data, selector, delegator, capture) {//add an ID to an event    varID =Zid (Element),//determine if there is an event object inside, and return without giving an empty arraySet = (Handlers[id] | | (Handlers[id] = [])); //I guess the words should be the same object can be bound to multiple events $ (' Li '). On ("click Hover")Events.split (/\s/). ForEach (function(event) {//determine if it is a ready event if it is directly tuned to the Ready function line      if(Event = = ' ready ')return$ (document). Ready (FN)//namespace Processing      varHandler =Parse (event)//Bind callbackHandler.fn =fn Handler.sel=selector//handler Object {e: "Clcik", ns: "", Fn:function, sel:undefined}        //Judge MouseEnter, MouseLeave, if it is, change the FN.      if(HANDLER.EinchHover) fn =function(e) {//Relatedtarget are mainly mouseover and mouseout attributes.        varRelated =E.relatedtargetif(!related | | (Related!== This&&!$.contains ( This, related))) returnHandler.fn.apply ( This, arguments)} //if Delegator doesn't preach, it's undefinde.Handler.del =delegatorvarcallback = Delegator | |fn Handler.proxy=function(e) {e=compatible (e)//Canceling event Propagation        if(E.isimmediatepropagationstopped ())returnE.data=Data//Callback Bindings        varresult = Callback.apply (element, E._args = = undefined?)[E]: [E].concat (E._args))if(Result = = =false) E.preventdefault (), e.stoppropagation ()returnresult} handler.i=set.length Set.push (handler)if(' AddEventListener 'inchElement)  {Element.addeventlistener (Realevent (HANDLER.E), Handler.proxy, Eventcapture (handler, capture))}) }

The Add function is basically like this, there are some parameters for the moment, we go to the back to see what these parameters are. Let's see how to Unbind

function Remove (element, events, FN, selector, capture) {    var id = Zid (element);    | | "). Split (/\s/). foreach (function(event) {      findhandlers (element, event, FN, selector). foreach (  function(handler) {        delete  handlers[id][handler.i]         if inch Element)          Element.removeeventlistener (Realevent (HANDLER.E), Handler.proxy, Eventcapture (handler, capture))})  }

It's easier to unbind. It's obvious in the last sentence

  Element.removeeventlistener (Realevent (HANDLER.E), Handler.proxy, Eventcapture (handler, capture))

The three parameters are generated in the Add function just now. Now explain the technical points inside the var id = zid (Element) This actually generates an ID for each callback so that it is convenient to find him at the time of deletion. And then handler is actually an empty literal object that adds a configuration attribute inside. In this case, we can use Hendler to manipulate some of the properties of this event; Well, we're going to go over the basics, let's take a look at how this event is handled

//it's like jquery. On the base on for parameter adjustment add for true binding$.fn.on =function(event, selector, data, callback, one) {varAutoremove, Delegator, $ This= This    //event exists, but the event is not a string    if(Event &&!)isstring (event)) {$.each (event,function(Type, fn) {$ This. On (type, selector, data, FN, one)}) return$ This    }    /*It's all in the right position .*/    //selector does not exist callback does not exist    if(!isstring (selector) &&!isfunction (callback) && callback!==false) Callback= data, data = selector, selector =undefined//data is a function or data is False    if(isfunction (data) | | data = = =false) Callback= data, data =undefined//if the callback returns false    if(Callback = = =false) Callback =Returnfalse//The above are not normal conditions. Here are some of the things we used to do    return$ This. each (function(_, Element) {//_ is an index element is an object      //One exists in the case      if(one) Autoremove =function(e) {Remove (element, E.type, callback)returnCallback.apply ( This, arguments)} //Selector exists      if(selector) Delegator =function(e) {//Get target element        varEVT, match = $ (e.target). Closest (selector, Element). Get (0)        if(Match && Match!==Element) {          //Set Event ObjectEVT =$.extend (Createproxy (E), {currenttarget:match, livefired:element})return(Autoremove | | callback). Apply (match, [Evt].concat (Slice.call (arguments, 1)))        }      }      //Here are some of the things we used to doAdd (element, event, callback, data, selector, delegator | |autoremove)}) }

There are actually two technical points in the first position of the adjustment, because the API is very flexible then will cause some parameters do not exist, then the parameter adjustment. Second. There is something in the API on (TYLE,SELECT,XX,XX,XX); okay. With the students know that this is the binding element of the extension of the binding (do not know how to express, anyway, is to narrow the scope of it) then how this is achieved? We will notice that there is something in the on function if (selector) delegator = function (e) {} This has actually changed silently to the object you are bound to. Then call the Add function, and everything is done.

Well, it's here today. I say the general idea, in fact, is to add remove as the top-level function, and then on/off for the lower layer function. As for bind, these functions are built on/off. And on/off is based on Add/remove. On/off is just a function of a simple parameter adjustment.

The students who read the source of the query should also find that the implementation of these frameworks are similar, but jquery is more complex.

Zepto Source Analysis------Event Chapter

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.