温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

js发布的订阅模式的作用有哪些

发布时间:2021-10-09 13:58:10 来源:亿速云 阅读:276 作者:柒染 栏目:编程语言

这篇文章将为大家详细讲解有关js发布的订阅模式的作用有哪些,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

1、发布订阅模式可以广泛应用于异步编程,这是一种取代回调函数的方案。

2、发布订阅模式可以取代对象之间硬编码的通知机制,一个对象不再需要明确调用另一个对象的接口。

实例

// 由于这些成员对于任何发布者对象都是通用的,故将它们作为独立对象的一个部分来实现是很有意义的。那样我们可将其复制到任何对象中,并将任意给定对象变成一个发布者。
// 如下实现一个通用发布者,定义发布者对象……
let publisher = {
  subscribers: {
    any: []
  },
  subscribe: function (fn, type = `any`) {
    if (typeof this.subscribers[type] === `undefined`) {
      this.subscribers[type] = [];
    }
    this.subscribers[type].push(fn);
  },
  unSubscribe: function (fn, type = `any`) {
    let newSubscribers = [];
    this.subscribers[type].forEach((item, i) => {
      if (item !== fn) {
        newSubscribers.push(fn);
      }
    });
    this.subscribers[type] = newSubscribers;
  },
  publish: function (args, type = `any`) {
    this.subscribers[type].forEach((item, i) => {
      item(args);
    });
  }
};
 
// 定义一个函数makePublisher(),它接受一个对象作为参数,通过把上述通用发布者的方法复制到该对象中,从而将其转换为一个发布者
function makePublisher(obj) {
  for (let i in publisher) {
    if (publisher.hasOwnProperty(i) && typeof publisher[i] === `function`) {
      obj[i] = publisher[i];
    }
  }
  obj.subscribers = { any: [] };
}
 
// 实现paper对象
var paper = {
  daily: function () {
    this.publish(`big news today!`);
  },
  monthly: function () {
    this.publish(`interesting analysis`, `monthly`);
  }
};
 
// 将paper构造成一个发布者
makePublisher(paper);
 
// 看看订阅对象joe,该对象有两个方法:
var joe = {
  drinkCoffee: function (paper) {
    console.log(`Just read ` + paper);
  },
  sundayPreNap: function (monthly) {
    console.log(`About to fall asleep reading this ` + monthly);
  }
};
 
// paper注册joe(即joe向paper订阅)
paper.subscribe(joe.drinkCoffee);
paper.subscribe(joe.sundayPreNap, `monthly`);
 
// 即joe为默认“any”事件提供了一个可被调用的方法,而另一个可被调用的方法则用于当“monthly”类型的事件发生时的情况。现在让我们来触发一些事件:
paper.daily();      // Just read big news today
paper.daily();      // Just read big news today
paper.monthly();    // About to fall asleep reading this interesting analysis
paper.monthly();    // About to fall asleep reading this interesting analysis
paper.monthly();    // About to fall asleep reading this interesting analysis

关于js发布的订阅模式的作用有哪些就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

js
AI