Last active
August 14, 2020 05:36
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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