0

Question

what is more suitable to express/collect object behavior, an IIFE or a variation of an object constructor? as it applies to the pub/sub pattern.

Is the choice to use one over the other purely stylistic, or am I not considering of other benefits/drawbacks than what I've shared below?

Object constructor

(I prefer OLOO via Kyle Simpson's style of behavior delegation from YDKJS ch.6 'this and objects').

benefits

  • We define can pub/sub object with member properties and methods

drawbacks

  • An argument that I see against using an object 'constructor' is that it suggests/encourages behavior delegation in the future
  • the pattern leaves room for polymorphism if developers are not careful

IIFE

benefits

  • the methods and properties can be made private i.e. closure-scoped properties and methods
  • Perhaps put more clearly, an IIFE would enforce encapsulation
  • The IIFE could later be made into a module as well

link to a simple pub/sub IIFE pattern from Addy Osmani

// 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)

or

/*!
* 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 ));
E_net4
  • 27,810
  • 13
  • 101
  • 139
Kyle Fong
  • 131
  • 3
  • 12
  • 1
    Your code with `Object.create` doesn't work as multiple "instances" [would share the same `topics` object](https://stackoverflow.com/questions/10131052/crockfords-prototypal-inheritance-issues-with-nested-objects/). Yes you do need a constructor for that, and no a constructor only means that it can be called multiple times, it doesn't give way to polymorphism or delegation. – Bergi May 25 '19 at 12:38

1 Answers1

0

I think its about how you read your code at the end of the day. Also, if i'm not mistaken, babel/webpack turn this into an IIFE anyway for transpilation/concatenation; Someone correct me if i'm wrong.