观察者模式

事件驱动模型,观察者模式

image

同一个事件,多个监听器

const EventEmitter = require("events");

const myEmitter = new EventEmitter();

// 这里是两个观察者,观察对应的对象,等待对象做出动作
myEmitter.on("newSale", () => {
  console.log("There was a new sale");
});

myEmitter.on("newSale", () => {
  console.log("Custumer name: Kihyun");
});

// 这是事件发出的对象
myEmitter.emit("newSale");

一个http请求的例子,监听到请求事件会console.log

const http = require("http");

const server = http.createServer();

server.on("request", (req, res) => {
  console.log("Request received!");
  console.log(req.url);
  res.end("Request received!");
});

server.on("request", (req, res) => {
  console.log("Another request 😀");
});

server.on("close", () => {
  console.log("Server closed!");
});

server.listen(8000, "127.0.0.1", () => {
  console.log("Waiting for request...");
});
posted @ 2022-06-18 03:00  kihyun  阅读(23)  评论(0编辑  收藏  举报