JSFiddle - React, Tailwind, and code Playground
JavaScript
// This observer object can be mixed into any object, giving it the basic
// API necessary to add and remove subscribers as well as emit events
var observer = {
// 'subscribers' will keep track of subscribers by event name
// each event name subscribed to will be a member name on
// this object, w/ the value as an array of objects containing
// the subscriber callback and optional function context
subscribers: {},
// the 'on' method is used by subscribers to add a callback
// to be invoked when a specific event is emitted
on: function (event, cb, context) {
this.subscribers[event] = this.subscribers[event] || [];
this.subscribers[event].push({
callback: cb,
context: context
});
},
// 'off' allows subscribers to remove their callbacks
off: function (event, cb, context) {
var idx, subs = this.subscribers[event],
sub;
if (subs) {
idx = subs.length - 1;
while (idx >= 0) {
sub = subs[idx];
if (sub.callback === cb && (!context || sub.context === context)) {
subs.splice(idx, 1);
break;
}
idx--;
}
}
},
// iterates over the subscriber list for
// a given event and invokes the callbacks
emit: function (event) {
var subs = this.subscribers[event],
idx = 0,
args = Array.prototype.slice.call(arguments, 1);
if (subs) {
while (idx < subs.length) {
sub = subs[idx];
sub.callback.apply(sub.context || this, args);
idx++;
}
}
}
};
// We're using jQuery's extend function to copy the observer
// object's members over a new object, creating the "jim" instance
var jim = $.extend({
dangItDoug: function (numberStolen) {
this.emit("stolenkill", numberStolen);
}
},...