Skip to content

Instantly share code, notes, and snippets.

@paulhhowells
Last active December 16, 2015 11:29
Show Gist options
  • Save paulhhowells/5427523 to your computer and use it in GitHub Desktop.
Save paulhhowells/5427523 to your computer and use it in GitHub Desktop.
register callback functions that fire on jQuery resize() — use for passing callbacks with arguments, or methods that use 'this' to reference parent object
/*jslint bitwise: true, eqeq: false, sloppy: true, white: true, browser: true, devel: true, indent: 2 */
/*globals phh, jQuery, window, console */
/*
unnecessary if you only need:
$(window).resize(function() {
// do something A
});
$(window).resize(function() {
// do something A
});
however if you want to pass a method that uses 'this' to refer to its parent object,
or to pass a function along with one or more arguments, then this code could be useful:
*/
var phh = phh || {};
(function ($) {
/*
* use resize.register(callback_function, optional_argument)
* to register callbacks that fire on window resize event
*/
var resize = (function () {
var callbacks = [];
$(window).resize(function () {
var
i,
callback;
for (i = 0; i < callbacks.length; i += 1) {
callback = callbacks[i];
if (callback.hasOwnProperty('arg')) {
callback.func(callback.arg);
} else {
callback.func();
}
}
});
return {
register : function (f, arg) {
var callback = {
func : f
};
if (arg) {
callback.arg = arg;
}
callbacks.push(callback);
}
};
}());
$(function () { // ready
// test that resize register works
resize.register(
function (val) {
console.log('registered: ' + val);
},
'test optional stored argument'
);
});
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment