How to write a PubSub 

in 15 mins 

& why you should do so


@jaseemabid 

gh:jaseemabid


Opinionated!

loves JavaScript, emacs, git. 
Fundamentally anti Microsoft


OR,


Why you don't need another 25kb 

pubsub.js 


What is pubsub ?






A SHORT FOR "PUBLISH AND SUBSCRIBE." 



Any piece of code can publish 

an event 

or message to a broker




any other piece of code can 

listen for that event


Well, fancy stuff allowed, obviously ;)


WHY ?


logically decouple object(s) 
that generate an event, 
and object(s) that act on it




What's the whole point ?


Loose Coupling !





Show me the code!!




Message Queue



var broker = new Pubsub();


Subscribe to events



broker.on('foo', function (m) {
console.log('Got the message ', m); });


Trigger events



broker.trigger('foo', 42);



Unsubscribe



broker.off('foo');


Implementation !!



Message Queue



    var Pubsub = function () {
        this._events = {};
    };



SUBSCRIBE TO EVENTS


Pubsub.prototype.on = function (type, handler) { if (this._events[type] === undefined) { this._events[type] = []; } this._events[type].push(handler); };



TRIGGER EVENTS

     Pubsub.prototype.trigger = function (event, message) {
        var events;

        if (this._events[event] instanceof Array) {
            events = this._events[event];
            events.forEach(function (e) {
                e.call(this, message);
            });
        }
    };

Unsubscribe



Pubsub.prototype.off = function (type) { if (this._events[type]) { delete this._events[type]; } };


*DEMO*


var broker = new Pubsub();

broker.on('foo', function (m) {
    console.log('Got the message ', m);
});

broker.trigger('foo', 42);>>Got the message  42
broker.trigger('foo', 26);
>>Got the message 26
broker.off('foo'); broker.trigger('foo', 'Never show this');



Moonshot ?


Now What?


pubsub

By jaseemabid

pubsub

  • 1,416