SoFunction
Updated on 2025-03-01

Example analysis of javascript custom event functions and usage

This article describes the functions and usage of JavaScript custom events. Share it for your reference, as follows:

Overview

Is it hard to come in handy for custom events?

Why custom events are difficult to come in handy, because js was not developed in modularly and rarely collaborated. Because events are essentially a communication method and a message, only when there are multiple objects and multiple modules, events may be needed for communication. Now that we have modularization, we can use custom events to collaborate between modules.

Where to use custom events?

Events are essentially a kind of message, and event mode is essentially an implementation of the observer mode. So where you can use the observer mode, you can naturally use the event mode. So, if:

1. When a target object changes, multiple observers need to adjust themselves.

For example: After I click on element A, element B shows the mouse position, element C shows the prompt, element D...

2. Module-based collaboration needs to be decoupled

For example: A is responsible for module A, B is responsible for module B, and module B needs to be completed before it can be run.

Traditional writing methods write logic in one method:

function doSomething(){
  A();
  B();
}

This requires modifying the click function of a for each extension, which is difficult to expand.

How to write custom events

//1. Create eventvar clickElem = new Event("clickElem");
//2. Register the event listener("clickElem",function(e){
  //Do something})
//3. Trigger event(clickElem);

As you can see, only the listener registered on the elem can listen to events triggered by elem through the dispatchEvent method. This is very boring. Send yourself a message to notify yourself of what to do.

To create custom events, please refer to: MDN:Creating_and_triggering_events

application

From the previous description of js custom event, we know that only the listener registered on A can listen to events triggered by element A through the dispatchEvent method.

The effect we want is that after another object does something, send us a message so that we can make corresponding changes. There is no way to do this: we can listen and trigger events on a public object, which makes sense.

Example 1: Notify multiple objects

To implement that after element A is clicked, element B shows the mouse position and element C shows the prompt. You can write it like this:

document:

import b from "./b"
import c from "./c"
var a = ("a");
("click",function(e){
  var clickA = new Event("clickA");
  (clickA);
});

Note: Although the variables entered in import are not used, they must not be omitted.

document:

var b = ("b");
("clickA",function(e){
   = "(128,345)";
})

document:

var c = ("c");
("clickA",function(e){
   = "You clicked A";
})

This way, the three modules do not need to care about the object at all, nor do they know the other party's existence. The coupling degree is very low and can be written independently without affecting each other. This is actually an implementation of the observer pattern.

Example 2: Game Framework

To develop a game, start the game, load pictures and music, after loading, rendering the scene and sound effects, loading and rendering are the responsibility of different people. You can write this way:

document:

import loadImage from "./loadImage"
import loadMusic from "./loadMusic"
import initScene from "./initScene"  
var start = ("start");
("click",function(e){
  ("The game begins!");
  (new Event("gameStart"));
})

document:

// Load the picture("gameStart",function(){
  ("Loading pictures...");
  setTimeout(function(){
    ("Loading image complete");
    (new Event("loadImageSuccess"));
  },1000);
});

document:

//Load music("gameStart",function(){
  ("Loading music...");
  setTimeout(function(){
    ("Loading music completed");
    (new Event("loadMusicSuccess"));
  },2000);
});

document:

// Render the scene("loadImageSuccess",function(e){
  ("Create a scene with pictures...");
  setTimeout(function(){
    ("Create a scene complete");
  },2000)
});
//Resource sound effects("loadMusicSuccess",function(e){
  ("Create sound effects with music...");
  setTimeout(function(){
    ("Create sound effect complete");
  },500)
});

The loading module and the rendering module do not affect each other and are easy to expand.

Carry information

In addition, events can also pass custom information:

var event = new CustomEvent('myEvent', { 'dataName': dataContent });
(event);

(Note: CustomEvent is required to pass custom information, not Event)

Then take it out in the listening function:

("myEvent",function(e){
  ();
})

This feature is very useful!

Attached:Click here to viewgithub example

PS: Here we will attach a javascript system's own event reference table for your reference and query:

A complete list of javascript events and functions:
http://tools./table/javascript_event

For more information about JavaScript, readers who are interested in reading this site's special topic:A complete collection of operations and techniques related to JavaScript events》、《Summary of JavaScript DOM skills》、《Summary of JavaScript Errors and Debugging Skills》、《Summary of JavaScript data structure and algorithm techniques》、《JavaScript traversal algorithm and skills summary"and"Summary of JavaScript mathematical operations usage

I hope this article will be helpful to everyone's JavaScript programming.