11th Chapter: Event System

Source: Internet
Author: User
Tags support microsoft

An event system is a very important part of a framework that responds to the various behaviors of the user.
The browser provides 3 levels of API to respond to the user's various behaviors .


1. The most primitive is written in the element tag.
2. Again within the script, the el.onxxx = function binding, collectively referred to as the DOM0 event system.
3. Finally, the multi-throw event system, an element of the same type of event can be bound to multiple callbacks, commonly known as the DOM2 event system.

Due to browser wars, two sets of APIs exist.

IE and Opera:
Binding event: El.attachevent ("on" + Type, callback)
Unload Event: El.detachevent ("on" + type. Callback)
Creation event: El.document.createEventObject ()
Distribution event: El.fireevent (type,event)

W3c:

Binding event: El.addeventlistener (Type,callback,[phase])
Unload event: El.removeeventlistener (Type,callback,[phase])
Creation Event: El.createevent (Types)
Initialization event: Event.initevent ()
Dispatch event: El.dispatchevent (Event)

From the number and form of the API, we provide a lot of complexity, relative to the more powerful, we will analyze each

First, let's start with a few simple examples, no need to use the framework. But the fact is that the entire event system is based on them.

    functionaddevent (EL, Callback, usecapture) {if(el.dispatchevent) {//FirstEl.addeventlistener (Type, callback,!!usecapture); } Else{el.attachevent ("On" +type, callback); }        returnCallback//return to callback for easy unloading    }    functionremoveevent (EL, type, callback, usecapture) {if(el.dispatchevent) {//FirstEl.removeeventlistener (Type, callback,!!usecapture); } Else{el.detachevent ("On" +type, callback)} }    functionfireEvent (el, type, args, event) {args= Args | | {}        if(el.dispatchevent) {//Firstevent = document.createevent ("htmlevents"); Event.initevent (Type,true,true); } Else{Event=Document.createeventobject (); }         for(varIinchArgsif(Args.hasownproperty (i)) {Event[i]=Args[i]}if(el.dispatchevent) {el.dispatchevent (event); } Else{el.fireevent (' On ' +type, event)} }

One, the flaw of onxxx binding way

OnXxx can be written either in the HTML tag or independently, as a special attribute of the element node, but as an ancient binding method it is difficult to anticipate the expansion of this aspect.

The following deficiencies are summarized:

1.onXXX new events for DOM3 or FF some private implementations are not supported, mainly with the following events :

Domactivate
Domattrmodified
Domattributenamechanged
Domcharacterdatamodified
domcontentloaded
Domelementnamechanged
Domfocusin
Domfocusout
Dommousescroll
domnodeinserted
Domnodeinsertedintodocument
Domnoderemoved
Domnoderemovedfromdcouemnt
Domsubtreemodified
Mozmousepixelscroll

2.onXXX only allows elements to bind one callback at a time, and repeated bindings flush out the previous bindings
3.onXXX callback without parameters in IE, the first parameter in the other browser callback is the event object .
4.onXXX can only be used during the bubbling phase .

Second, the defects of attachevent

Attachevent is also supported by Microsoft's Api,opera added in IE5, and for onxxx mode, it allows the same element to bind multiple callbacks in the same event, the so-called multi-throw event mechanism. But there are only a lot of trouble, there are a few defects.

1.ie only support Microsoft's event system, DOM3 events are not supported.
2.IE the This in attchevent callback is not pointing to the bound element, but window!
3.IE when the same event binds multiple callbacks, callbacks are not triggered sequentially in the order of binding!
There are too many differences between event object and the Currenttarget in 4.IE, some cannot be on the number, such as the
The 5.IE still supports only the bubbling phase.


With regard to event objects, the general trend is that, when IE9 supports the set of APIs, it is very helpful for us to implement event proxies.

Third, the defects of AddEventListener

This set of APIs is not flawless, after all, standards are always lagging behind the reality, the rest of the standard browser has its own abacus, there are inconsistencies between them.

1. The new events are very unstable , and there may be widespread obsolescence, and in the early days of the sizzle selector engine, there were a few sentences.

    false );    Document.addeventlistener (false);    Document.addeventlistener (false);

Now that the three events have been scrapped (and, to be exact, all the changes are over), FF14 and Chrome18 began using mutationobserver instead.

2.Firefox does not support focusin,focus events, nor does it support domfocusin,domfocusout, and is now reluctant to replace Dommousescroll with MouseWheel. Chrome does not support MouseEnter and MouseLeave.

Therefore, do not assume that standard browsers will definitely achieve the standard event, all feature detection is essential.

3. The third, fourth, and fifth standard parameters.

The third parameter, usecapture only a very new browser is optional. For example, FF6 or before is optional, for security purposes, make sure that the third parameter is a Boolean .

4. Instability of event members .
The internet is copied from the browser, the people have spent so long, inevitably with the standard inconsistent.

FF Event.timestamp returned 0, the bug,2004 year was submitted and was not repaired until 2011.

Safari under Event.target may return text node

Event.defaultprevented, Event.istrusted and Stopimmediatepropagation method, before the standard browser is unified with Getpreventdefault method to do this thing, in the jquery source code, found that it is handled with isdefaultprevented.

The IsTrusted property is used to indicate whether the current event is triggered by a user's behavior, such as triggering the Click event with a real mouse click, or by a script (using event construction methods, such as Event.initevent). istrusted Please pay more attention to

5. Standard browsers have no way to simulate Proprtychange events like Ie6-8 .

Although the standard browser has input, domattrmodified,mutationobserver, but propertychange than the weak explosion. PropertyChange can listen for multiple property changes, not just value values. In addition it does not differentiate between attribute and property. Therefore, both el.xxx = YYY or El.setattribute (XXX,YYY) are exposed to this event.

Http://www.cnblogs.com/rubylouvre/archive/2012/05/26/2519263.html (determine if the browser supports domattrmodified)

Four, Dean Edward's Addevent.js source analysis

This is an event system that emerged early in the prototype era. The source of the jquery event system. Highlights are as follows:

1. Consciously block the difference between the default behavior and the event propagation interface between IE and the Internet Explorer.
2. Dealing with the order of IE execution callbacks
3. Dealing with this point problem of IE
4. No platform detection code, because it is built using the most common and primitive onxxx
5. Complete cross-browser (IE4 and NS4).

Omit Source analysis here

http://dean.edwards.name/weblog/2005/10/add-event/

//written by Dean Edwards, 2005//With input from Tino Zijdel, Matthias Miller, Diego Perini//http://dean.edwards.name/weblog/2005/10/add-event/functionaddevent (element, type, handler) {if(Element.addeventlistener) {Element.addeventlistener (type, handler,false); } Else {        //assign each event handler a unique ID        if(!handler.$ $guid) handler.$ $guid = addevent.guid++; //Create a hash table of event types for the element        if(!element.events) element.events = {}; //Create a hash table of event handlers for each element/event pair        varHandlers =Element.events[type]; if(!handlers) {Handlers= Element.events[type] = {}; //Store the existing event handler (if there is one)            if(element["on" +Type]) {handlers[0] = element["on" +type]; }        }        //Store the event handler in the hash tablehandlers[handler.$ $guid] =handler; //assign a global event handler to doing all the workElement["on" + type] =handleevent; }};//a counter used to create unique IDsAddevent.guid = 1;functionremoveevent (element, type, handler) {if(Element.removeeventlistener) {Element.removeeventlistener (type, handler,false); } Else {        //Delete the event handler from the hash table        if(Element.events &&Element.events[type]) {            Deleteelement.events[type][handler.$ $guid]; }    }};functionHandleevent (event) {varReturnValue =true; //Grab the Event object (IE uses a global event object)Event = Event | | Fixevent (( This. ownerdocument | | This. Document | | This). ParentWindow | |window). event); //get a reference to the hash table of event handlers    varHandlers = This. Events[event.type]; //execute each event handler     for(varIinchhandlers) {         This. $ $handleEvent =Handlers[i]; if( This. $ $handleEvent (Event) = = =false) {returnvalue=false; }    }    returnreturnvalue;};functionFixevent (event) {//Add standard event MethodsEvent.preventdefault =Fixevent.preventdefault; Event.stoppropagation=fixevent.stoppropagation; returnevent;}; Fixevent.preventdefault=function() {     This. returnvalue =false;}; Fixevent.stoppropagation=function() {     This. cancelbubble =true;};

But the blog post of Dean Edward can see a lot of corrections and useful patches. For example, since all the corrections are directed at IE, then the standard browser with AddEventListener on the line. It is also mentioned that when clicking an event in an IFRAME, the event object does not have an issue, submit the following useful patches.

    Event = Event | | Fixevent (((this this). ParentWindow | | window). event);


The 54th reply, directly leads to the creation of the jquery data cache system, in order to avoid the interleaved reference output memory leaks, the proposed element is assigned a UUID, all callbacks are placed in an object to store.

But as the event went on, the user discovered that OnXxx had an irreversible and irreparable memory leak in IE, so, turning to the earlier version of jquery, 1.01 was copied Dean Edward's, 1.1.31 version, starting with the suggestion of absorbing 54 uuid, and using attach/ RemoveEventListener binding Events--each element is bound only once. All callbacks are then called in handleevent-like functions.

( This chapter is longer and will be updated as follows:)

Five, jQuery1.8.2 's event module overview

Six, JQuery.event.add source interpretation

Seven, JQuery.event.remove's source code interpretation

Eight, the source of JQuery.event.dispatch interpretation

Nine, JQuery.event.trigger's source code interpretation

Ten, jquery fixes for event objects

11. Repair of Roller events

12, MouseEnter and MouseLeave event repair

13, focus and repair of focusout events

14, the old version of the Submit event proxy implementation of IE

XV, the compatibility of the Oninput event

Previous chapter: The Tenth Chapter: Property Module Next Chapter: 12th Chapter: Chapter Asynchronous Processing

11th Chapter: Event System

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.