search
HomeOperation and MaintenanceSafetyHow to use javascript to implement custom event functions

Overview

Custom events are hard to come in handy?

Why it is difficult for custom events to come in handy, because js was not developed in a modular manner in the past, and there was little collaboration. Because the essence of an event is a communication method and a message, only when there are multiple objects and multiple modules, it is possible to use events for communication. Now with modularization, custom events can be used to collaborate between modules.

Where can I use custom events?

The essence of an event is a kind of message. The event pattern is essentially the implementation of the observer pattern. So where the observer pattern is used, the event pattern can also be used. Therefore, if:

1. A target object changes, multiple observers are required to adjust themselves.

For example: after I click element A, element B displays the mouse position, element C displays a prompt, and element D...

2. Module collaboration needs to be decoupled

For example: A is responsible for module A, and B is responsible for module B. Module B needs to run after A has finished running.

The traditional way of writing is to write the logic in a method:

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

In this way, the click function of a must be modified every time it is expanded, which is not easy to expand.

How to write custom events

//1、创建事件
var clickElem = new Event("clickElem");
//2、注册事件监听器
elem.addEventListener("clickElem",function(e){
  //干点事
})
//3、触发事件
elem.dispatchEvent(clickElem);

As you can see, events triggered by elem through the dispatchEvent method can only be listened to by listeners registered on elem. This is very boring. Send yourself a message to tell yourself what to do.

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

Application

We know from the description of the previous js custom event: Element A passes dispatchEvent Events triggered by methods can only be listened to by the listener registered on A.

The effect we want is that after other objects do something, they 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 realize that after element A is clicked, element B displays the position of the mouse, and element C displays a prompt, you can write like this:

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 = "你点了A";
})

Written in this way, the three modules do not need to care about the objects at all, and do not know the existence of each other. The degree of coupling is very low, and they 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, and after loading, render the scene and sound effects. Loading and rendering are performed by different person is responsible. You can write like this:

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("游戏开始!");
  document.dispatchEvent(new Event("gameStart"));
})

File: loadImage.js

// 加载图片
document.addEventListener("gameStart",function(){
  console.log("加载图片...");
  setTimeout(function(){
    console.log("加载图片完成");
    document.dispatchEvent(new Event("loadImageSuccess"));
  },1000);
});

File: loadMusic.js

//加载音乐
document.addEventListener("gameStart",function(){
  console.log("加载音乐...");
  setTimeout(function(){
    console.log("加载音乐完成");
    document.dispatchEvent(new Event("loadMusicSuccess"));
  },2000);
});

File: initScene. js

//渲染场景
document.addEventListener("loadImageSuccess",function(e){
  console.log("使用图片创建场景...");
  setTimeout(function(){
    console.log("创建场景完成");
  },2000)
});
//渲染音效
document.addEventListener("loadMusicSuccess",function(e){
  console.log("使用音乐创建音效...");
  setTimeout(function(){
    console.log("创建音效完成");
  },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 });
document.dispatchEvent(event);

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

Then take it out in the listening function:

document.addEventListener("myEvent",function(e){
  console.log(e.dataName);
})

The above is the detailed content of How to use javascript to implement custom event functions. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool