Return to Snippet

Revision: 12099
at March 2, 2009 13:53 by johnloy


Initial Code
/*
@author gwilliams
From the article http://justanotherdeveloper.co.uk/2008/07/24/publisher-subscriber-pattern/
 */

var Publisher = function(){
 
    var _subscribers = [];
 
    return {
 
        /*
         * Pushes the subscribers callback function into
         * the private _subscribers property.
         */
        subscribe: function(fn){
            _subscribers.push(fn);
        },
 
        /*
         * Method is used to unsubscribe a subscribers callback function
         * from the publisher.
         */
        unsubscribe: function(fn){
 
            _newSubscribers = []; // Create an empty subscriber array
 
            /*
             * Loop through the _subscribers array, checking to see
             * whether the function in 'fn' matches any function in
             * the _subscribers array, if it doesn't match, push it
             * in the _newSubscribers array.
             */
            for (var i = 0; i < _subscribers.length; i++) {
                if (_subscribers[i] !== fn) {
                    _newSubscribers.push(fn);
                }
            }
 
            /*
             * Now the _newSubscribers array only contains the callback
             * methods we want we can re-assign it to the private
             * _subscribers property.
             */
            _subscribers = _newSubscribers;
        },
 
        /*
         * Wipes the subscriber list
         */
        wipe: function(){
 
            _subscribers = [];
 
        },
 
        /*
         * Returns all of the current subscribers in an array
         */
        getSubscribers: function(){
            return _subscribers;
        }
 
        /*
         * The notify method is used to invoke all of the callback methods
         * in the _subscribers array, o is the property to be sent to the
         * subscriber method, this can be anything from a string to an object
         * or even JSON.
         */
        notify: function(o){
             for (var i = 0; i < _subscribers.length; i++) {
                _subscribers[i].call(o);
            }
        }
 
    }
 
};

Initial URL

                                

Initial Description

                                

Initial Title
Class to implement publisher

Initial Tags
textmate

Initial Language
Other