Skip to content

Instantly share code, notes, and snippets.

@Tythos
Last active August 14, 2020 05:36
Show Gist options
  • Save Tythos/9d6a332749c05e635885e0315350ce3e to your computer and use it in GitHub Desktop.
Save Tythos/9d6a332749c05e635885e0315350ce3e to your computer and use it in GitHub Desktop.
Single-file JavaScript module: Attaches pub/sub behavior to the given object or constructor
/* Attaches pub/sub behavior to the given object. Returns a function that
attaches pub/sub behavior, including an *eventListeners* property, to the
given object or prototype function. Usage is simple; assume TestObj is a
constructor:
> pubsub(TestObj);
> var to = new TestObj();
> to.subscribe('trigger', function(eventObj) {
console.log(this);
console.log(eventObj);
});
> to.publish('trigger', {
timestamp: (new Date()).toUTCString()
});
You can also directly attach to any object. Tags are case-insensitive:
> let o = {"one": 1, "two": 2};
> pubsub(o);
> o.subscribe("STUFF_HAPPENS", console.log);
> o.publish("stuff_happens", { "context": this });
*/
if (typeof (define) != "function") { var define = require("sfjm").define.bind(exports); var window = {}; }
define(function (require, module, exports) {
function pubsub(obj) {
var tgt = obj;
if (obj.prototype) {
tgt = obj.prototype;
}
tgt.publish = publish.bind(tgt);
tgt.subscribe = subscribe.bind(tgt);
tgt.eventListeners = {};
}
function publish(eventTag, eventObj) {
if (typeof (eventObj) == 'undefined') { eventObj = {}; }
if (Object.keys(this.eventListeners).indexOf(eventTag) < 0) {
this.eventListeners[eventTag] = [];
}
this.eventListeners[eventTag].forEach(function (listener) {
listener.call(this, eventObj);
}, this);
}
function subscribe(eventTag, listener) {
if (Object.keys(this.eventListeners).indexOf(eventTag) < 0) {
this.eventListeners[eventTag] = [];
}
this.eventListeners[eventTag].push(listener);
}
return Object.assign(pubsub, {
"__uni__": "com.github.gist.tythos.pubsub",
"__semver__": "1.0.0",
"__author__": "code@tythos.net",
"__license__": "MIT" // SPDX Identifier
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment