事件机制-events
基础例子
例子 1: 单个事件监听器
const eventEmitter = require("events");
class Man extends eventEmitter {}
const man = new Man();
man.on("hello", function (val) {
console.log("man say hello", val);
});
man.emit("hello", 1);
man.emit("hello", 2);
例子 2 同个事件 多个事件监听器
const eventEmitter = require("events");
class Man extends eventEmitter {}
const man = new Man();
man.on("hello", function () {
console.log("man say hello");
});
man.on("hello", function () {
console.log("man say hello again");
});
man.emit("hello");
例子 3: 只运行一次的事件监听器
const eventEmitter = require("events");
class Man extends eventEmitter {}
const man = new Man();
man.on("hello", function () {
console.log("man say hello");
});
man.once("hello", function () {
console.log("man say hello once");
});
man.emit("hello");
man.emit("hello");
例子 4: 注册时间监听器前,事件先触发
const eventEmitter = require("events");
class Man extends eventEmitter {}
const man = new Man();
man.emit("hello", 1);
man.on("hello", function (index) {
console.log("man say hello", index);
});
man.emit("hello", 2);
例子 5: 异步执行,还是顺序执行
const eventEmitter = require("events");
class Man extends eventEmitter {}
const man = new Man();
man.on("hello", function () {
console.log("man say hello");
});
man.emit("hello");
console.log("woman say hello");
例子 6: 移除事件监听器
const eventEmitter = require("events");
class Man extends eventEmitter {}
const man = new Man();
function hello(params) {
console.log("man say hello");
}
man.on("hello", hello);
man.emit("hello");
man.removeAllListeners("hello", hello);
man.emit("hello");
相关链接
https: