laitimes

Section 61 Simulate and Customize Events Event-Web Front-End Development -JavaScript-Wang Wei

author:Zero point programmer

This content is the courseware of "Javascript Video for Web Front-end Development", please cooperate with the "Javascript" video course of Master Brother.

Simulated events:

Events are often triggered by user actions or through other browser functions, or javascript can be used to trigger a specific event at any moment, just like an event created by a browser, that is, a trigger event is simulated by Javascript;

The DOM2 level specifies the way to simulate specific events, which is supported by standard browsers, and IE has its own way of simulating events;

Event simulation in the DOM:

An event object can be created on a doucment object using the createEvent(type) method, which accepts a type string parameter representing the type of event to be created;

The type parameter, which can only pass values defined in the event module, at the DOM2 level, all these strings are in the form of a plural in English, while at the DOM3 level they become singular; the string can be one of the following:

Event: Generic Event Class;

UIEvents: Generalized UI events, mouse events and keyboard events are inherited from UI events, DOM3 level is UIEvent;

MouseEvents: Generalized mouse events, DOM3 level is MouseEvent;

KeyboardEvent:

MutationEvents: Generalized DOM change events, DOM level 3 is MutationEvent;

HTMLEvents: Generalized HTML events, there is no corresponding DOM3 level event, because in the DOM3 level event, the HTML event is scattered into other categories;

TextEvents: DOM3 level is TextEvent;

CustomEvent: Custom events;

There are other event modules, such as: SVGEvents, MessageEvent, ProgressEvent, AnimationEvent, TransitionEvent, etc.;

DOM2 level events do not specifically specify keyboard events, and give provisions for keyboard events in DOM3 level events; in fact, there is currently no browser supporting DOM3 level keyboard events; but on the basis of existing methods, keyboard events can be simulated in several ways;

Once the event object is created, it also needs to be initialized with information about the event; each type of event object has a special method that allows the event object to be initialized by passing in the appropriate data for it, but the name of this method of different types is also different, depending on the parameters used in createeEvent();

The event object of the Event module can be initialized using the Event.initEvent() method; syntax: event.initEvent(type, bubbles, cancelable); arguments: type: defines the event name; bubbles: a Boolean value, whether it bubbles; cancelable: a Boolean value, whether it can be canceled; such as:

Event modules and their initialization methods:

UIEvents:event.initUIEvent;

MouseEvents:initMouseEvent;

MutationEvents:initMutationEvent;

HTMLEvents:event.initEvent;

TextEvent:event.initTextEvent;

KeyboardEvent:event.initKeyboardEvent;

CustomEvent:event.initCustomEvent;

The parameters in these initialization methods are different and are determined by their event type, such as:

The final step in simulating an event is to trigger the event using the detachEvent() method, which requires passing in an event object that represents the event to be triggered; all DOM nodes that support events support this method;

After triggering an event, the event can be like a normal event, it can also bubble, and it can also normally trigger the execution of the corresponding event handler;

The dispatchEvent() method returns a boolean value, which is false when the event is cancelable (cancelable as true) and at least one of the event's event handlers call preventDefault(); otherwise returns true; otherwise returns true;

If the diskevent() method is called and the event is not initialized, it throws a UNSPECIFIED_EVENT_TYPE_ERR exception, or an uncaught exception if the event type is null or the event handler is an empty string;

Simulate mouse events:

The method creates and returns a simulated mouse event object with a method called initMouseEvent() that specifies information about the mouse event; the method accepts 15 parameters, one-to-one with each of the typical properties of the mouse event, as follows:

type: indicates the type of event to be triggered (for example: click);

bubbles: Indicates whether the event should bubble; for accurately simulating mouse events, it should be set to true

cancelable: indicates that the event can be canceled; for precision, it should be set to true;

view (AbstractView): The view associated with the event, this parameter is almost always set to doucment.defaultView;

detail: Detailed information about the event, this value is generally only used by the event handler, but is usually set to 0;

screenX : the X coordinate of the event relative to the screen;

screenY: the Y coordinate of the event relative to the screen;

clientX (integer): the X coordinate of the event relative to the viewport;

clientY (integer): the Y coordinate of the event relative to the viewport;

ctrlKey (Boolean): whether the Ctrl key is pressed, the default is false;

altKey (Boolean): whether the Alt key is pressed, the default is false;

shiftKey (Boolean): whether the Shift key is pressed, the default is false;

metakey (Boolean): whether the Meta key is pressed, the default is false;

button (integer): which mouse button was pressed, the default is 0;

relatedTarget : represents an event-related object, this parameter is only used when simulating mouseover and mouseout;

Where the first four parameters are critical to the correct trigger event, all the remaining parameters are only used in the event handler;

When an event object is passed to the sessionEvent() method, the target property of the object is automatically set;

In a compatible DOM browser, other mouse events can also be simulated in the same way, such as dblclick;

Simulated keyboard events:

DOM3 specifies that a keyboard event can be created by calling createeEvent() and passing in "keyboardEvent"; the returned event object will contain an initKeyboardEvent() method that accepts the following parameters:

type: indicates the type of event to be triggered;

bubbles: Indicates whether the event should bubble;

cancelable: indicates that the event is something that can be canceled;

view (AbstractView): The view associated with the event. This parameter is almost always set to doucment.defaultView;

key (string): represents the key code of the pressed key;

location (integer): indicates where the key was pressed: 0 represents the default main keyboard, 1 means left, 2 means right, 3 represents numeric keypad, 4 represents mobile device (that is, virtual keyboard), 5 represents the handle;

ctrlKey:

altKey:

shiftKey:

metaKey:

repeat: how many times the key was pressed in the line;

Since the use of keypress events is not recommended at the DOM3 level, this technique can only be used to simulate keydowns and keyup events, such as:

But this parameter order is not normal in IE, but it can use generic events;

First create a generic event and then call the initEvent() method to initialize it, that is, add keyboard event-specific information to the event object (or not), such as:

Here, generic events must be used, not UI events, because UI events do not allow new properties to be added to the event object;

Simulating events like this, although they trigger keyboard events, do not write text to the text box, which is caused by the inability to accurately simulate keyboard events;

Simulated change events:

You can use createeEvent ("MutationEvents") to create a change event object containing the initMutationEvent() method, which accepts parameters as: type, bubbles, cancelable, relatedNode, preValue, newValue, attrName, and attrChange;

Other change events are also created in the above format, only need to change the parameters;

Simulate HTML events:

By creatingEvent ("HTMLEvents"), it can be initialized using the object's initEvent() method;

Custom DOM events:

DOM3 level also defines "custom events", which are not triggered natively by the DOM, and are designed to let developers create their own events;

To create a custom event, you can call the createEvent ("CustomEvent") method, and the returned object has a method called initCustomEvent(), which receives 4 parameters:

type: Indicates the type of event to be triggered, such as "keydown";

detail: any value, saved in the detail property of the event object;

Custom event objects that you create can be dispatched in the DOM just like any other event, such as:

Event simulation in IE:

IE8 and below is not supported for DOM simulation events, it has a dedicated set of APIs, which is similar to the DOM idea: first create an event object, then assign it the corresponding information, and then use the object to trigger the event;

Calling the document.createEventObject() method creates an event object in IE that does not accept arguments and returns a generic event object; then, manually add all the necessary information to the object; finally, call the fireEvent() method on the target, which accepts two numbers: the name of the event handler and the event object; when calling the fireEvent() method, The srcElement and type attributes are automatically added to the event object; other properties must be added manually; simulating any IE supported events follows the same pattern;

The properties added to the event object can be arbitrary, without any restrictions, even if the added properties IE do not support it, the added properties have no effect on the event, because only event processing will use them;

Using the same pattern can also simulate triggering a keypress event;

As with the DOM, no characters are output in the text box;

Since the event objects for mouse, keyboard, and other events are no different, you can use generic objects to trigger any type of event;

Custom events:

document.createEvent() is no longer recommended, it is recommended to use constructors of various event types to create events;

Event class:

Represents an event that occurs in the DOM, which is the base class for other types of events and contains properties and methods that apply to all events;

Constructor: Event(), which creates and returns an Event object; syntax: event = new Event(typeArg, eventInit); argument: typeArg, a string, representing the name of the created event;

EventInit is optional and is a dictionary object of type EventInit that accepts the following fields:

"bubbles", optional, of type Boolean, with a default value of false, indicating whether the event is bubbling;

"cancelable", optional, boolean type, default value is false, indicating whether the event can be canceled;

"composed", optional, Boolean type, default value is false, indicating whether the event will trigger a listener outside the Shadow DOM root node;

The typeArg event type, i.e. it can be a built-in event or a custom event;

After the event is created, it needs to be triggered manually using the butterflyEvent();

Note: Use the event event.isTrusted property to distinguish whether it is triggered by the user or the script;

Also, custom events should use addEventListener, as on<vent > are only used in built-in events;

IE does not support creating events using constructors, only the document.createEvent() method instead; for example:

as:

Many built-in events have default behavior, but for custom events, there is no default behavior; but when the method is called, the dispatchEvent() method returns false; so the method is used in custom events for special purposes, for example, by calling the method, the event handler can send a signal based on this signal in order to decide how the following should be done, such as:

example:

Subclasses of common Event:

CustomEvent: Custom event class;

DeviceOrientationEvent: Rotate the mobile device event class; (e.g., get the x, y, and Z axe angles of the rotation of an event, etc.)

DragEvent: Drag-and-drop event class, which inherits both Event and MouseEvent classes;

ErrorEvent: Error event class;

FocusEvent: Represents a focus-related event class, inherited from the UIEvent class;

KeyboardEvent: Keyboard event class

MouseEvent: Mouse event class, inherited from the UIEvent class;

MutationEvent: Class of change events;

TouchEvent: Touch event class, inherited from the UIEvent class;

UIEvent; user interface event class, inherited from the Event class;

WheelEvent: Mouse wheel or similar input device event class;

The standard properties of different event types are not the same, such as the clientX and clientY of mouse events, such as:

But if you use the Event constructor (replace MouseEvent with Event), it is simply ignored because the ClientX and ClientY properties are not its standard properties;

To create a CustomEvent event:

For example, replace the new Event in the previous example with new CustomEvent, and the result is the same; but the CustomEvent object has a detail property that can be used to pass some information, which can be any type of data, such as:

It is even possible to instantiate an Event object directly in the sessionEvent() method, such as:

Create the MouseEvent event, syntax: event = new MouseEvent(typeArg, mouseEventInit); the parameter typeArg is the event name, and the optional parameter mouseEventInit is the dictionary object that initializes MouseEvent, which works the same as the initMouseEvent() method above, such as:

Create the KeyboardEvent event, syntax: event = new KeyboardEvent (typeArg, KeyboardEventInit), the parameter typeArg is the event name, KeyboardEventInit is a dictionary object, has the following values:

"key", optional, defaults to "", corresponding to the value of keyboardEvent .key;

"code", optional, defaults to "", corresponding to the value of KeyboardEvent.code;

"location", optional, defaults to 0, unsigned long type, sets the value of KeyboardEvent.location.

"ctrlKey", optional, defaults to false, Boolean type, sets the value of KeyboardEvent.ctrlKey.

"shiftKey", optional, defaults to false, Boolean type, sets the value of KeyboardEvent.shiftKey.

"altKey", optional, defaults to false, Boolean type, sets the value of KeyboardEvent.altKey.

"metaKey", optional, defaults to false, Boolean type, sets the value of KeyboardEvent.metaKey.

"repeat", optional, defaults to false, Boolean type, sets the value of KeyboardEvent.repeat.

"isComposing", optional, defaults to false, Boolean type, sets the value of KeyboardEvent.isComposing.

"charCode", optional, defaults to 0, unsigned long type, sets the value of KeyboardEvent.charCode (deprecated).

"keyCode", optional, defaults to 0, unsigned long type, sets the value of KeyboardEvent.keyCode (deprecated).

"which", optional, defaults to 0, unsigned long type, sets the value of KeyboardEvent.which (deprecated).

KeyboardEventInit dictionaries can also accept dictionary field values from UIEventInit and EventInit; for example:

Set the KeyboardEventInit parameter:

How custom events are implemented:

An event is essentially a message, and an event pattern is a design pattern called an observer, which is a technique for creating loosely coupled code;

The observer pattern consists of two types of objects: the subject and the observer; the subject is responsible for publishing events, and the observer observes the subject by subscribing to these events; a key concept of the pattern is that the subject does not know anything about the observer, that is, it can exist on its own and operate normally even if the observer does not exist; on the other hand, the observer knows the subject and can register the callback function (event handler) of the event; when it comes to the DOM, the DOM element is the subject, and your event processing code is the observer;

The most original custom events, such as:

A custom event is essentially a call to a function; for built-in events, the event name is usually defined in advance by the API;

The simplest custom events, such as:

Simple event classes:

Event objects can register multiple events, such as:

It is also possible to modify the sessionEvent() method to pass a similar event object, such as:

apply:

Section 61 Simulate and Customize Events Event-Web Front-End Development -JavaScript-Wang Wei

Read on