2

as subject states, I want to attach events to my objects and trigger its action at future so I can do asynchronous stuff without callbacks and Qs.

I dont want to attach & pollute any particular DOM or the document.

3
  • Do you want to attach a function to an object which modifies it when you call the function later or do you want to execute a function on an object which causes a function to be called when a certain specified condition is met ? Commented Aug 5, 2014 at 23:23
  • Can you show an example? May be pseudo-code. Commented Aug 5, 2014 at 23:25
  • You should look for publish/subscribe pattern or maybe also mixin pattern Commented Aug 5, 2014 at 23:53

1 Answer 1

2

Publish / Subscribe pattern

var utils = utils || {};
utils.publishSubscribe = (function() {

    var publishSubscribe = {};

    // Storage for topics that can be broadcast 
    // or listened to
    var topics = {};

    // An topic identifier
    var subUid = -1;

    // Publish or broadcast events of interest
    // with a specific topic name and arguments
    // such as the data to pass along
    publishSubscribe.publish = function( topic, args ) {

        if ( !topics[topic] ) {
            return false;
        }

        var subscribers = topics[topic],
            len = subscribers ? subscribers.length : 0;

        while (len--) {
            subscribers[len].func( topic, args );
        }

        return this;
    };

    // Subscribe to events of interest
    // with a specific topic name and a
    // callback function, to be executed
    // when the topic/event is observed
    publishSubscribe.subscribe = function( topic, func ) {

        if (!topics[topic]) {
            topics[topic] = [];
        }

        var token = ( ++subUid ).toString();
        topics[topic].push({
            token: token,
            func: func
        });
        return token;
    };

    // Unsubscribe from a specific
    // topic, based on a tokenized reference
    // to the subscription
    publishSubscribe.unsubscribe = function( token ) {
        for ( var m in topics ) {
            if ( topics[m] ) {
                for ( var i = 0, j = topics[m].length; i < j; i++ ) {
                    if ( topics[m][i].token === token ) {
                        topics[m].splice( i, 1 );
                        return token;
                    }
                }
            }
        }
        return this;
    };

    return publishSubscribe;
}());

Usage

utils.publishSubscribe.subscribe( "inbox/newMessage", function( topic, data ) {
    console.log( "A new message was received: ", data );
})

utils.publishSubscribe.publish( "inbox/newMessage", [{
      sender: "[email protected]",
      body: "Hey there! How are you doing today?"
}]);

source: Addy Osmani – Learning JavaScript Design Patterns

Sign up to request clarification or add additional context in comments.

2 Comments

interesting, so the way to immitate events is by using callbacks.
I would regard unsubscription as an essential aspect of publish/subscribe, especially in the absence of weak references. Otherwise, event publishers which substantially outlive subscribers will cause memory leaks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.