Skip to content

Instantly share code, notes, and snippets.

@sberdyug
Forked from Kcko/pubsub.js
Created June 29, 2022 22:10
Show Gist options
  • Save sberdyug/a3c3bda9ae9cce20da2d30160f147b55 to your computer and use it in GitHub Desktop.
Save sberdyug/a3c3bda9ae9cce20da2d30160f147b55 to your computer and use it in GitHub Desktop.
(function($) {
var o = $({});
var calledEvents = {};
$.subscribe = function() {
o.on.apply(o, arguments);
if (arguments[0] in calledEvents)
{
var eventName = arguments[0];
var callback = arguments[1];
var clbArgs = [
{type: eventName}, // event
].concat(calledEvents[eventName][0]);
callback.apply(o, clbArgs);
}
};
$.unsubscribe = function() {
o.off.apply(o, arguments);
};
$.publish = function() {
o.trigger.apply(o, arguments);
var eventName = arguments[0];
var args = Array.prototype.slice.call(arguments, 1);
calledEvents[eventName] = args;
};
}(jQuery));
// USAGE
$.subscribe('document/kunda', function(e, a, b) {
console.log('A');
});
$.publish('document/kunda', ['AA', 'BBB']);
$.subscribe('document/kunda', function(e, a, b) {
console.log('B');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment