Throttled Resize Management

Define a list of things to do on resize and add to it at any time later. Uses Ben Alman's throttle/debounce plugin to keep calls down to once per 250ms.

by Brian Cribb

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-throttle-debounce/1.1/jquery.ba-throttle-debounce.min.js"></script>
<h2>Manage Resize</h2>
<p class="feedback--resize"></p>
<p class="feedback--other-resize"></p>

JavaScript

var SITE = {
    counter : 0, // Used to update markup on resize so you don't have to look in the console.
	resizeTasks : [], // Initialize this to an empty array so it will be defined when called.
	init : function() {
        // Setting up resize function to throttle.
		$(window).resize( $.throttle( 250, SITE.manageResize ) );

        // Initial tasks to be run on page load and then on every resize.
		var initTasks = {
            func: function(myMessage){
                SITE.counter ++;
                $('.feedback--resize').html( myMessage + " (" + SITE.counter + ")" );
            },
            args : ["I'm resizing!"]
		};
		initTasks.func("I ran once during setup!"); // Initial call of our resize task.
		SITE.addResizeTask(initTasks); // Adding this task to the list for future use.
	},
	addResizeTask : function(task) {
        // Adds a function and its arguments to an array for use on resize.
		console.log('adding task');
        $('body').append('<p>Adding task...</p>'); // Just to show that it worked.
        
        // FORMAT: var myTask = {func:myfunction, args:[arg1,arg2]}
		task.args = task.args || []; // If it isn't defined, set to empty array.
		SITE.resizeTasks.push(task); // Add to the tasks list.
	},
	manageResize : function() {
		/*  Cycle through resize tasks. We loop through the tasks array and pass in 
            the values for each object to the "apply" JavaScript method. The 'func' 
            property is the function and the 'args' property is the arguments in the 
            form of an array. The context isn't important in this case, but if it 
            matters to you then you can set some value for "this" before using apply().
            
            This allows us to add other tasks later, after the site's init function 
            has completed.
        */
        
		for (var i = 0; i < SITE.resizeTasks.length; i++) {
			var task = SITE.resizeTasks[i];
			task.func.apply(this, task.args);
		};
	}
}
SITE.init();

//...