JavaScript Advanced Programming Chapter 13 events

Source: Internet
Author: User
Tags deprecated event listener

Xiao Kee

The interaction between JS and HTML is implemented through events, where events occur at an instant of interaction and can be scheduled using event listeners (or event handlers). DOM2 Event module As far as possible to standardize the event, however, DOM3 added some additional processing, coupled with the difference between the BOM and browser, event processing can be very complex. But the basic concepts still need to be understood.

Navigation

    • The concept of event flow go
    • Event handlers (HTML, DOM0, DOM2, and IE work in general, cross-browser processing) go
    • Event object. Dom and IE differences, cross-browser processing) go
    • Event type (listing various common event types to learn about some common types) go
    • Memory and performance (consider performance issues and memory footprint, reduce the number of usage events and purge in a timely manner, with emphasis on event delegation) go
    • Analog events Go
Event Flow
    • Drawing concentric on paper, when pointing to one of the circles actually points to all the circles, then how to determine the order of the point, the same as the event, so the time flow is normalized.
    • The event stream is used to describe the order in which events are accepted from the page.
    • Mainstream: Event bubbling. Ie. Passing events up.
    • Other: Event capture. Netscape. In contrast to the event bubbling order, it is primarily to capture events.
    • Complete DOM Event flow (DOM2 level): Event handling has three stages: event capture, Target, and event bubbling phase.
Event handlers
  • Event (click)--function to respond to an event: event handler/Event listener (such as onclick)
  • It is divided into HTML event handlers, DOM0 event handlers, DOM2 event handlers, ie event handlers, so you need to discuss cross-browser processing at the end.
  • An HTML event handler that takes an event handler as a property of an element and executes the JS code in its value.
    • JS code note the handling of some escape characters.
    • The code of the event handler can access any code in the global scope.
    • Pros: The way you extend scopes, you can access element objects through event, this, and you can access the fields of other forms through the name value of the form.
    • Disadvantages: 1, time difference-can be solved by try-catch, 2, different browsers on the scope of the chain processing different, 3, the problem of smooth degradation.
  • DOM0 level Event handling.
    • The element is handled by its properties: Element.onclick = function () {dosomething ();};
    • Is the method of the element, which is the inside of the function that points to this element.
    • Delete method: Element.onclick = null;
  • DOM2 Level Event Handling
    • AddEventListener ()/removeeventlistener () for handling and deleting events
    • 3 Parameters: Event name to be processed, function to handle, Boolean value (true--capture phase call event handling; false--bubbling phase Call)
    • Scope: This also points to the element being called.
    • Advantage: You can bind multiple event handlers. And the DOM0 is not supported. These programs are executed in the binding order.
    • Note: The arguments in RemoveEventListener () need to be exactly the same as in AddEventListener () to effectively dismiss the event, so if the event handler function is an anonymous function, it cannot be processed.
    • Event handlers are not typically registered during the event capture phase.
  • IE Event handlers
    • Attachevent ()/detachevent (): 2 parameters: Event handler name (!! Unlike DOM2, it is not the click Type but the onclick type), the event handler function. The default is to register event handlers for the bubbling phase.
    • Scope: Runs in the global scope, this points to window.
    • You can also bind multiple event handlers for an element. These programs are executed in reverse order.
    • DetachEvent () also needs to pass in the same parameter, and cannot handle anonymous functions.
  • Cross-browser event handlers
    • Using JS Library
    • Proper use capability testing: PDF P372. Write the binding and Unbind function in an object (and then add a series of methods and properties for cross-browser event objects); Focus on the bubbling phase. There is still a shortage, but enough.
Events Object (event, etc.)
    • It is divided into the DOM object in the event object and IE, so the cross-browser situation is also considered.
    • The event exists only during the execution of a handler. Once the event handler finishes executing, it is destroyed.
    • The event object is passed to the DOM (either DOM0 or DOM2) when it processes the handler.
      • has some properties and methods
      • Note This, currenttarget, and target: Inside the event handler, this is always equal to Currenttarget, which points to the location where the event program is registered, and the target points to the button.
      • The Event.type property can determine the event type: Click, MouseOver, Mouseout, and so on
      • Block default behavior: Event.preventdefault (); (or return false?) When the Event.cancelable property is true, it can take effect.
      • Block bubbling or capturing phase: event.stoppropagation ();
      • Determine the event execution phase: Event.eventphase property.
    • Objects in IE
      • Gets event:window.event or (when the event is accessed with attachevent () Add Event orhtml property) event
      • There are properties and methods that are functionally equivalent to those in the DOM.
      • Srcelement instead of target
      • Block default behavior: ReturnValue = False, equivalent to Preventdefault.
      • Block bubbling: cancelbubble = True equals Stoppropagation (), but only prevents bubbling.
    • Cross-browser event object to refine that object in the previous section. See PDF page 379.
Event Type
  • The DOM3 level Event module is updated on the basis of the DOM2 level event module, specifying some of the following events
    • UI event: Triggered when the user interacts with elements on the page
    • Focus Event
    • Mouse events
    • Wheel Event
    • Text event: Triggered when text is entered in a document
    • Keyboard events
    • Composition event: Triggered when a character is entered for an IME (input Method Editor)
    • Change event: Triggers when the underlying DOM structure is changed
    • Change name event: waste except
  • In addition, HTML5 defines a set of events
  • The browser implements some proprietary events on the BOM and Dom
  • UI events: Many are related to the Window object or form control, and are classified as HTML events in DOM2.
    var issupported = document.implementation.hasFeature ("htmlevents", "2.0");     var issupported = document.implementation.hasFeature ("Uievent", "3.0");
    • Load event:
      • Two ways to define the OnLoad event handler: By invoking the JS code (which can be handled by invoking the cross-browser event object in the previous section), and processing it in the HTML properties (which corresponds to the window, it needs to be specified on the <body> element).
      • Can be specified on window (document), in fact, before specifying the onload event for other elements (such as IMG, link, script, etc.), it is generally necessary to ensure that the OnLoad event of window has been executed.
      • In general, DOM2-level events require the OnLoad event to be bound on the <body> element rather than the window object, but all browsers implement the OnLoad event on the window for backwards compatibility.
      • Note when specifying the onload event, specify the event before specifying the SRC attribute. In general, the new image does not have to be downloaded after the document is added, as long as the SRC attribute is set to start the download. (Note the processing of the image object)
      • The <script><link> element can also specify the onload event, and they will not start the download until the Src/href attribute is specified and added to the document. It can be used to determine whether a script or an external style sheet has finished loading.
    • Unload event: As the name implies, whenever a user switches from one page to another, that is triggered. Can be used to dereference to prevent memory leaks. The OnUnload event is largely used with the OnLoad event. Note, however, that because unload is triggered after it is unbound, the element or object it binds to does not necessarily exist and needs to be handled with care.
    • Resize event: As the name implies. Bound on the Window object or the <body> element, so the Event.target value will be document. Because each browser handles it differently, it can cause frequent recurring triggers, so be careful not to pass in too much code.
    • Sroll event: Binding on the Window object or the <body> element actually reacts to the position of the element or container and can be monitored by the scrollleft/scrolltop of the BODY element in promiscuous mode, or in standard mode (except Safari) to monitor through HTML. It is also possible to frequently repeat the trigger, so the incoming code needs to be cautious.
  • Focus Event

    var issupported = document.implementation.hasFeature ("FocusEvent", "3.0");
    • Triggers when the page Gets or loses focus, and with the Document.hasfocus () method and the Document.activeelement property, the user's dynamics are known.
    • Blur/focus: The element loses/receives focus and does not bubble.
    • Domfocusout/domfocusin: The element loses/gets the focus, bubbling is the generic version of the HTML event blur/focus. Opera use, DOM3 level event deprecated.
    • Focusout/focusin: equivalent to the HTML event Blur/focus, will bubble, compared to the above one of the events, get more extensive support.
    • The focus moves from one element in the page to another, triggering in the following order:
      • Focusout--focusin---blur--domfocusout--focus---domfocusin
      • Target is obviously the element that loses focus and the element that gets focus.
  • Mouse and Wheel Events
    var issupported = document.implementation.hasFeature ("mouseevents", "2.0");     var issupported = document.implementation.hasFeature ("MouseEvent", "3.0");
    • Click (enter)/dbclick,mousedown/mouseup, mouseenter/mouseleave,mouseover/mouseout; MouseWheel (Wheel event) Note that other events cannot be triggered by the keyboard except that the click can be triggered with a carriage return, so avoid using other times when considering the accessibility browser. In addition to MouseEnter and MouseLeave time will bubble.
    • The relationship between Mousedown/mouseup and click and Dbclick is expressed in such a trigger sequence:mousedown->mouseup->click->mousedown->mouseup-> Dbclick
    • Some coordinates location: client area coordinates position Clientx/clienty (mouse event trigger, mouse in viewport coordinates information), page coordinates position Pagex/pagey (mouse event trigger, mouse in the page coordinates information, actually Pagex = clientx+ document.body.scrollleft/document.documentelement.scrollleft), screen coordinate position screenx/screeny (relative to the location information of the entire computer screen).
    • Modifier key: Mouse event triggered by the time Event.shiftkey/ctrlkey/altkey/metakey, as a Boolean value.
    • Related elements (MouseOver and MouseUp): Good understanding of concepts. The Even.relatedtarget attribute points to this related element. There are fromelement properties for mouseover in IE, MouseUp have toelement properties, which can be processed across browsers. PDF P392.
    • mouse button (MouseDown or MouseUp): Event.button property of the 0,1,2 corresponding to the main button, wheel button and secondary button, IE8 set 0-7 numbers, you can normalize the IE model to the DOM mode, cross-browser processing. PDF 393.
    • More information about the event:
      • Detail property: Records the number of times MouseDown and MouseUp (clicks) occur successively in the same pixel area.
      • IE's altleft, ctrlleft, OffsetX, OffsetY, Shifitleft
    • Roller Event MouseWheel, bubbling
      • The Wheeldelta property records the offset: a multiple of 120 forward and a multiple of 120 backwards.
      • Before Opera9.5 (Client.engine.opera && Client.engine.opera < 9.5 See the client Detection chapter), the positive and negative sign is the opposite.
      • Firefox's Dommousescroll event function is the same, however its detail property is a multiple of-3 on the forward wheel and a multiple of 3 backwards.
      • The ability to detect and implement cross-browser applications. See PDF P396.
    • Touch Device: Touch screen.
  • Keyboard and Text events
    • The DOM2 level does not specifically define related events, basically follows DOM0, and DOM3 defines a number of new events.
    • 3 Keyboard events: KeyDown (All keys)/keypress (character key)/keyup. 1 Text Event TextInput
    • Press the character key to trigger the order: Keydown->keypress->keyup
    • Press the following non-character key, triggering order: KeyDown-KeyUp
    • If you press and hold the corresponding key, KeyDown or keypress will always be triggered.
    • TextInput is a supplement to KeyPress, there are two differences: 1, the former is only valid for editable regions, the latter is valid for any element that can get focus. 2. The former is only triggered when the exact character is entered, and the latter is also valid when the input is similar to BACKSPACE.
    • Key code (KeyDown, KeyUp event): Event.keycode property, returns the ASCII code for the corresponding key, regardless of the shift state. There are some differences between browsers. The obtained ASCII code can be converted to actual characters with String.fromCharCode ().
    • Character encoding (keypress): The Event.charcode property, only valid at KeyPress event, returns the key code for the corresponding character, at which point the Event.keycode property may be 0 or key. In the case of cross-browser processing, it is generally necessary to determine whether to support charcode, if not supported, use KeyCode. See PDF P400.
    • DOM3 new events, properties and methods, mostly not yet popular
      • Key/char Property (deprecated): key denotes a literal character (k/k) or a key name ("Shift"), Char also represents a literal character when the character is pressed, and in other cases it is empty. IE9 only supports Key,safari 5 and Chrome has an alternative keyidentifier property to do the same for non-characters, and the character returns a string representing Unicode in a certain format. Cross-browser processing is required here. See PDF P401.
      • Location property (deprecated): Indicates where the pressed key is located on the keyboard or which peripherals are part of it. Safari and Chrome have keyloction override properties. Note Cross-browser processing.
      • Modifier keys: DOM3 the new Getmodifierstate () method, but shiftkey/altkey/ctrlkey/metakey enough with Dom properties.
      • TextInput events: The differences with KeyPress are mentioned above.
      • Inputmethod Property: Represents how text is entered into a text box. The method used to detect the text input into the control to verify its validity.
    • Keyboard events in the device: various peripherals. Touch the device.
    • Composite event (DOM3 new, processing IME input, not very useful)
          issupported = Document.implementation.hasFeature ("Compositonevent", "3.0");
      • IME input: Often used to enter characters that cannot be entered directly by the keyboard (such as Japanese, etc.), in most cases multiple keys are pressed at the same time to enter a character (hence "compound").
      • Event: Compositionstart/compositionupdate/compositionend
      • Property: Event.data
  • Change events (DOM structure changes)
    • Many events are known for their names and are not to be described. DOM3 abolished many, two examples of triggering a change event when deleting and adding nodes.
    • Remove nodes from the DOM structure, triggering order:
      • Trigger the Domnoderemoved event on the deleted node: Event.target is the node, Event.relatednode, like the ParentNode property of the node, points to its parent node, bubbling.
      • The Domnoderemovedfromdocument event is triggered on this node and all its child nodes, not bubbling (note that the child node is tested at the time of the generic test, not the node, to prevent the node from removing from the structure that affects the binding event).
      • Triggers the Domsubtreemodified event on its parent node.
    • Inserting nodes into the DOM structure, triggering the order:
      • The domnodeinserted event is triggered on the node, Event.target points to the node, and Event.relatednode also points to its parent node. Bubble.
      • The Domnodeinsertedintodocument event is triggered on this node and does not bubble, so you must add the event handler for it before inserting the node.
      • Triggers the domsubtreemodifed event on its parent node. Bubble.
    • HTML5 Event (Specifies that some DOM3 did not have time to regulate the event)
      • ContextMenu event (the context of the processing element, which appears when the element is right-clicked): Bubbling. Mouse events (general right or CTRL + click). can be masked (with the usual event method).
      • Beforeunload Event: Implement some actions before the page is unloaded to provide an opportunity to prevent users from leaving the interface. Used in conjunction with Event.returnvalue.
      • Domcontentloaded event: Compared to the Load event, the complete DOM tree will be triggered after completion, regardless of whether the JS file, CSS files, etc. have been downloaded. The point is that users interact with the page earlier. Will bubble. It is usually bound on window (document).
      • ReadyStateChange event (IE): Provides information related to the loading state of a document or element, typically with the readystate attribute, which can represent 5 status values (to confirm the existence and initialization of objects and the loading situation). Can be applied on many elements to detect its condition, but the element does not necessarily go through 5 states, and not all elements have the same state meaning, which needs to be considered in practice.
      • Pageshow and Pagehide events (Firefox, Opera): For the round trip cache feature (that is, to speed up the response of the page to the back and Forward buttons). Understand Bfcache. The Event.persisted property indicates whether it is loaded from the Bfcache.
      • Haschange event: The URL parameter list (including all strings after #) is triggered when a change occurs, mainly in Ajax, using the URL parameter sequence to save the state or navigation information. Properties Oldurl, Newurl can implement Location.hash functions. The latter is generally used because there are not many browsers that support Oldurl and Newurl.
    • Device events (cell phone or tablet, specifically used for re-study)
      • Orientationchange event for IOS (browse mode: Landscape or portrait)
      • Mozorientation Event for Firefox 3.6
      • Deviceorientation Events
      • Devicemotion Events
    • Touch and gesture events (for touch screen, specific to re-study): basically introduced in iOS2.0 Safari.
Memory and performance
    • JS requires careful use of the number of event handlers, which is a single-process run code that delays script run events. The more objects (functions) are at the same time, the larger the memory is occupied. There are some optimization methods:
    • event delegate (resolves an issue with too many event handlers)
      • Using a bubbling program to resolve, for example, click to bubble, specify a handler only in the DOM tree at the highest level possible (without compromising the quality of the feature implementation).
      • Even delegate events directly on the document.
    • Remove event Handlers: Remove obsolete, different "empty event handlers" when not needed. It can also help with logical problems.
      • Two causes of "empty event handlers":
        1. When an element with an event handler is removed from the page, the element floats and cannot retract its event handlers and some references, which are still stored in memory.
        2. Before uninstalling the page, there is no cleanup event handler, causing the number of lingering objects to increase repeatedly.
      • Workaround
        1. Release the event handler before removing the element. The efficient use of event delegates does not directly add event handlers to the elements that need to be deleted, but instead delegate to high-level elements.
        2, uninstall the page, through the OnUnload event handler to remove all the event handlers, to reduce the amount of work to remove, you can effectively use the event delegate. So it seems that something added via onload needs to be removed via onunload.
Simulation Events
    • DOM: Document.createevent (). Passing in the appropriate parameters simulates a mouse, keyboard, or other event, and can even customize DOM events. Returns the corresponding method or object for further operation.
    • In IE: simulate any event that has the same pattern: Create an Event object with Document.createeventobject ()--add property values and methods to initialize this event object (a custom procedure)---finally through fireevent The () method calls this event, passing in two arguments: the event name and the events object.

JavaScript Advanced Programming Chapter 13 events

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.