Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Angular window resize service
// http://www.paulirish.com/2009/throttled-smartresize-jquery-event-handler/
//
// debouncing function from John Hann
// http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
var debounce = function (func, threshold, execAsap) {
var timeout;
return function debounced () {
var obj = this, args = arguments;
function delayed () {
if (!execAsap) {
func.apply(obj, args);
}
timeout = null;
}
if (timeout) {
clearTimeout(timeout);
} else if (execAsap) {
func.apply(obj, args);
}
timeout = setTimeout(delayed, threshold || 100);
};
};
// smartresize
var sr = 'smartresize';
jQuery.fn[sr] = function(fn){ return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };
/**
* @fileOverview Singleton instance that will watch for window resize events.
*/
require('../plugins/jquery-debounce');
/**
* Singleton instance that will watch for window resize events.
*
* @constructor
*/
var Resize = module.exports = function($rootScope, $window, $log) {
this.$rootScope = $rootScope;
this.$window = $window;
this.$log = $log;
$(window).smartresize(this._onResize.bind(this));
};
/** @const {string} The event triggered on root scope */
Resize.EVENT_NAME = 'front-resize';
/**
* Wrapper for rootScope $on.
*
* @param {Function} fn The callback.
* @return {Function} Invoke to unbind.
*/
Resize.prototype.$on = function(eventName, fn) {
return this.$rootScope.$on(Resize.EVENT_NAME, fn);
};
/**
* Triggers on window resize.
*
* @param {Object} jqueryEvent the jQuery event object.
* @private
*/
Resize.prototype._onResize = function(jqueryEvent) {
this.$rootScope.$emit(Resize.EVENT_NAME, jqueryEvent);
};
angular.module('reveal.front')
.service('ResizeService', ['$rootScope', '$window', '$log',
Resize,
]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment