⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 15.03 - building an observer api.js

📁 JS设计模式源代码
💻 JS
字号:
function Publisher() {  this.subscribers = [];}Publisher.prototype.deliver = function(data) {  this.subscribers.forEach(    function(fn) {      fn(data);    }  );  return this;};Function.prototype.subscribe = function(publisher) {  var that = this;  var alreadyExists = publisher.subscribers.some(    function(el) {      if ( el === that ) {        return;      }    }  );  if ( !alreadyExists ) {    publisher.subscribers.push(this);  }  return this;};Function.prototype.unsubscribe = function(publisher) {  var that = this;  publisher.subscribers = publisher.subscribers.filter(    function(el) {      if ( el !== that ) {        return el;      }    }  );  return this;};var publisherObject = new Publisher;var observerObject = function(data) {  // process data  console.log(data);  // unsubscribe from this publisher  arguments.callee.unsubscribe(publisherObject);};observerObject.subscribe(publisherObject);

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -