其他分享
首页 > 其他分享> > 观察者模式

观察者模式

作者:互联网

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

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 

标签:myEmitter,http,log,观察者,模式,server,console,const
来源: https://www.cnblogs.com/kihyunBlog/p/16387553.html