Skip to main content
3 of 3
Fixed hyperlink.
glampert
  • 17.2k
  • 4
  • 30
  • 89

Javascript singleton to notify different objects of changes in viewport size

I'm working on a singleton object to manage size changes in the viewport, I wanted it to be a singleton because there may be different unrelated objects that need to be notified when a change in viewport dimensions has occurred. So I came up with this solution based on the singleton design pattern found in here.

var CAResizeManager = ( function () {

    var instance;

    function init() {

        var o_actions   = [];
        var o_cache_pos = {};
        var o_timeout;

        /* 
         * Custom 'addEvent' function;
         */
        addEvent( window, 'resize', function () {

            /* 
             * Clear timeout if resize is called severla times in short timespan.
             */
            clearTimeout( o_timeout );

            o_timeout = setTimeout( function () {

                var o_viewport_size = getViewportSize();
                /* 
                 * Loop through the actions array to pass new viewport size;
                 */
                for ( var i = o_actions.length - 1; i >= 0; i-- ) {
                    var o_func = o_actions[ i ];

                    if ( o_func ) {
                        o_func( o_viewport_size );
                    }
                }

            } ,300 );

            
        } );

        return {
            addAction: function ( arg_func ) {

                /*
                 * Generates a unique id to identify action.
                 */
                var i_id = Math.random().toString().replace( '0.', '' );

                o_actions.push( arg_func );
                
                /* 
                 * Store position in an object to avoid looping through the 
                 * actions array.
                 */ 
                o_cache_pos[ i_id ] = o_actions.length === 0 ? 0 : o_actions.length - 1;                
                
                /*
                 * Return id to external object.
                 */
                return i_id;
            },
            removeAction: function ( arg_id ) {

                var i_index = o_cache_pos[ arg_id ]; 

                /* 
                 * Check if id exists;
                 */
                if ( i_index ) {
                    return;
                }

                /* 
                 * Remove action from array
                 */
                o_actions.splice( i_index, 1 );

                /* 
                 * Delete positon from cache;
                 */
                delete o_cache_pos[ arg_id ];

            }
        };
    }

    return {
        getInstance: function () {

            if ( !instance ) {
                instance = init();
            }

            return instance;
        
        }
    }

} )();