Created
May 20, 2015 12:22
-
-
Save thanpolas/467821ce1a09c48f3315 to your computer and use it in GitHub Desktop.
Angular window resize service
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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); }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @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