为发布/订阅模式权衡模块v。对象构造函数?

时间:2019-05-24 22:37:32

标签: javascript constructor scope closures iife

问题

什么更适用于表达/收集对象行为,IIFE或对象构造函数的变体?,因为它适用于发布/订阅模式。

是选择只使用一种样式还是另一种样式,还是我没有考虑下面所分享的其他好处/缺点?

对象构造函数

(我更喜欢通过YDKJS ch.6“ this and objects”的Kyle Simpson行为委派样式进行OLOO操作。)

好处

  • 我们用成员属性和方法定义can pub / sub对象

缺点

  • 我反对使用对象“构造函数”的观点是 它建议/鼓励将来进行行为授权
  • 如果开发人员不小心,该模式将为多态留有余地

IIFE

好处

  • 可以将方法和属性设为私有,即封闭范围的属性和方法
  • 也许更明确地说,IIFE将强制执行封装
  • IIFE以后也可以做成一个模块

从Addy Osmani链接到simple pub/sub IIFE pattern

// pubsub implementation, mine
let pubsub = {
  topics: {},

  publish: function ( topic, message ) {
    if (this.topics.hasOwnProperty(topic)) {
      // add message to topic and update # messages in topic
      this.topics[topic].messages.push(message)
      this.topics[topic].messages.count = this.topics[topic].messages.count++;
    } else {
      // create new topic object
      this.topics[topic] = {}
      this.topics[topic].subscribers = []
      this.topics[topic].messages = []
      this.topics[topic].count = 1
    }
  },

  subscribe: function ( entityID, topic ) {
    // if topic exists, add entity to list of subscriptions for that topic
    if (this.topics.hasOwnProperty(topic)) {
      this.topics[topic].subscribers.push(entityID)
    } else {
      throw new TypeError("the topic must exist first before subscribing to it")
    }
  },

  unsubscribe: function ( entityID, topic ) {
    if (this.topics.hasOwnProperty(topic)) {
      if (this.topics[topic].subscribers.includes(entityID)) {
        for (let i = 0, j = this.topics[topic].subscribers.length; i < j; i++) {
          if (this.topics[topic].subscribers[i] === entityID) {
            this.topics[topic].subscribers.splice(i, 1);
          }
        }
      } else {
        throw new TypeError("an entity must be subscribed to the topic before unsubscribing")
      }
    } else {
        throw new TypeError("the topic must exist first before unsubscribing from it")
    }
  },
}

let pubsubInstance = Object.create(pubsub)
pubsubInstance.subscribe(object, topic)

/*!
* Pub/Sub implementation
* http://addyosmani.com/
* Licensed under the GPL
* http://jsfiddle.net/LxPrq/
*/


;(function ( window, doc, undef ) {
   'use strict';

    var topics = {},
        subUid = -1,
        pubsubz ={};

    pubsubz.publish = function ( topic, args ) {

        if (!topics[topic]) {
            return false;
        }

        setTimeout(function () {
            var subscribers = topics[topic],
                len = subscribers ? subscribers.length : 0;

            while (len--) {
                subscribers[len].func(topic, args);
            }
        }, 0);

        return true;

    };

    pubsubz.subscribe = function ( topic, func ) {

        if (!topics[topic]) {
            topics[topic] = [];
        }

        var token = (++subUid).toString();
        topics[topic].push({
            token: token,
            func: func
        });
        return token;
    };

    pubsubz.unsubscribe = function ( token ) {
        for (var m in topics) {
            if (topics[m]) {
                for (var i = 0, j = topics[m].length; i < j; i++) {
                    if (topics[m][i].token === token) {
                        topics[m].splice(i, 1);
                        return token;
                    }
                }
            }
        }
        return false;
    };

    var getPubSubz = function(){
        return pubsubz;
    };

    window.pubsubz = getPubSubz();

}( this, this.document ));

1 个答案:

答案 0 :(得分:0)

我认为这是关于您如何在一天结束时阅读代码的。另外,如果我没记错的话,babel / webpack还是将其转换为IIFE进行转译/串联;如果我错了,有人纠正我。