Examples of functions and usage of javascript custom events and Analysis of javascript instances
This document describes the functions and usage of javascript custom events. We will share this with you for your reference. The details are as follows:
Overview
Is it difficult to use custom events?
Why is it difficult for custom events to come in handy, because js was not modularized and rarely collaborated in the past. Because events are essentially a communication method and a message, only when multiple objects and modules exist can events be used for communication. Now with modularization, you can use custom events to collaborate between modules.
Where can I get a custom event?
An event is essentially a message, and an event mode is essentially an observer mode. The event mode can also be used where the observer mode is used. Therefore, if:
1. When a target object changes, multiple observers must adjust its own.
For example, after I click element a, Element B displays the mouse position, element C displays the prompt, and Element D .....
2. Module-based collaboration needs to be decoupled
For example, module A, Module B, and Module B must be executed after module A is run.
In traditional writing, the logic is written in a method:
function doSomething(){ A(); B();}
In this way, the click function of a needs to be modified for each extension, which is difficult to expand.
Writing custom events
// 1. Create the Event var clickElem = new Event ("clickElem"); // 2. register the Event listener elem. addEventListener ("clickElem", function (e) {// do something}) // 3. trigger event elem. dispatchEvent (clickElem );
We can see that only the listener registered on elem can listen to events triggered by elem through the dispatchEvent method. This is boring. I sent a message to myself to notify myself of what to do.
For details about how to create a custom event, see MDN: Creating_and_triggering_events.
Application
From the preceding description of js custom events, we know that only the listener registered on A can listen to events triggered by element A through the dispatchEvent method.
What we want is to send a message to us after another object has done something, so that we can make corresponding changes. There is no way to do this: we can listen to and trigger events on a public object, which makes sense.
Example 1: Notify multiple objects
After clicking a on Element A, Element B displays the mouse position, and element C displays the prompt, which can be written as follows:
File: a. js
import b from "./b"import c from "./c"var a = document.getElementById("a");a.addEventListener("click",function(e){ var clickA = new Event("clickA"); document.dispatchEvent(clickA);});
Note: although the imported variables are not used, they must not be omitted.
File B. js:
var b = document.getElementById("b");document.addEventListener("clickA",function(e){ b.innerHTML = "(128,345)";})
File c. js:
Var c = document. getElementById ("c"); document. addEventListener ("clickA", function (e) {c. innerHTML = "you clicked ";})
In this way, the three modules do not need to care about objects at all, and do not know the existence of each other. The coupling degree is very low. They can be written independently without affecting each other. This is actually the implementation of an observer mode.
Example 2: Game framework
To develop a game, start the game, load pictures and music, after loading, render the scene and sound effects, loading and rendering are the responsibility of different people. You can write as follows:
File: index. js
Import loadImage from ". /loadImage "import loadMusic from ". /loadMusic "import initScene from ". /initScene "var start = document. getElementById ("start"); start. addEventListener ("click", function (e) {console. log ("game started! "); Document. dispatchEvent (new Event (" gameStart "));})
File: loadImage. js
// Load the image document. addEventListener ("gameStart", function () {console. log ("load image... "); setTimeout (function () {console. log ("image Loading completed"); document. dispatchEvent (new Event ("loadImageSuccess") ;}, 1000 );});
File: loadMusic. js
// Load the music document. addEventListener ("gameStart", function () {console. log ("load music... "); setTimeout (function () {console. log ("completed music loading"); document. dispatchEvent (new Event ("loadMusicSuccess") ;}, 2000 );});
File: initScene. js
// Render the scene document. addEventListener ("loadImageSuccess", function (e) {console. log ("Use Image Creation scenario... "); setTimeout (function () {console. log ("scenario created") ;}, 2000)}); // renders the audio document. addEventListener ("loadMusicSuccess", function (e) {console. log ("use music to create sound... "); setTimeout (function () {console. log ("sound effect created") ;}, 500 )});
The loading and rendering modules do not affect each other and are easy to expand.
Carrying Information
In addition, events can also pass custom information:
var event = new CustomEvent('myEvent', { 'dataName': dataContent });document.dispatchEvent(event);
(Note: You must use CustomEvent instead of Event to pass custom information)
Then, retrieve the following information from the listener:
document.addEventListener("myEvent",function(e){ console.log(e.dataName);})
This function is very useful!
Appendix:Click here to viewGithub example
PS: Here is a reference table for javascript system events for your reference:
Javascript events and functions:
Http://tools.jb51.net/table/javascript_event