17-事件机制-events

91 阅读2分钟

事件机制-events

// events模块式node的核心模块之一,几乎所有常用的node模块都继承了events模块。比如http,fs等,模块本身非常简单,API虽然也不少,但常见的就那么几个,简单举例

基础例子

例子 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 has worken up 1
  // man has worken up 2
});
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 say hello
// 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");

// man say hello
// man say hello once
// man say 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 say hello 2
});
man.emit("hello", 2);

例子 5: 异步执行,还是顺序执行

// 例子很简单,但是非常重要,究竟是代码1先执行,还是代码2先执行,这点差异,无论对于我们理解别人的代码还是自己的node编程都非常的关键
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");

// man say hello
// 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");
// man say hello  只执行一次

相关链接

https://nodejs.org/api/events.html