Emitter Test

by dpnminh

JavaScript

function Emitter() {
  var events = new Map();

  return {
    subscribe: function(event_name, callback) {
      //If events has event_name, then get the event Subscription and push to it.
      //Else create new event, subscription and add to events.

      var isEventExisted = events.has(event_name),
        index = 0;

      if (isEventExisted) {
        var subscriptions = events.get(event_name);
        index = subscriptions.push(callback) - 1;
      } else {
        events.set(event_name, [callback]);
      }

      //Return an object with reference to this
      return {
        unsubscribe: function() {
          var status = true;

          if (index > -1) {
            var subscriptions = events.get(event_name);
            if (subscriptions) {
              subscriptions.splice(index, 1);
            }

            return status;
          }

          return !status;
        }
      };
    },
    emit: function(event_name, ...params) {
      var isExisted = events.has(event_name);

      if (isExisted) {
        var subscriptions = events.get(event_name);

        if (subscriptions) {
          for (var i = 0; i < subscriptions.length; i++) {
            var subscription = subscriptions[i];

            if (subscription instanceof Function) {

              //Trigger outside of loop
              (function(func, args) {
                setTimeout(function() {
                  func(...args);
                });
              })(subscription, params);
            }
          }
        }
      }

      return isExisted;
    }
  }
}

var emitter = new Emitter();
var subscriber1 = emitter.subscribe('event_1', function(name){console.log(name);});
var subscriber2 = emitter.subscribe('event_1', function(name, id){console.log(`${name} ${id}`);});
var subscriber3 = emitter.subscribe('event_1', function(name, id, gender){console.log(`${name} ${id} - gender: ${3}`);});

emitter.emit('event_1', "Maya", "32", "female");
var subscriber12 =...