david-d
5/11/2015 - 7:56 PM

Window events to broadcast through the app.

Window events to broadcast through the app.

'use strict';

// Modules
var $      = require('jquery');
var lodash = {
	debounce: require('lodash/function/debounce')
};

// Local variables
var _previousScroll = null;
var _scrollTimeout  = null;
var _resizeTimeout  = null;
var wTop            = null;



/**
 * Setup scroll and resize.
 */
function init () {
	$(window).on('scroll', lodash.debounce( _scrollEvents, 25, {
		'leading': true,
		'maxWait': 50,
		'trailing': true
	}));

	$(window).on('resize', lodash.debounce( _resizeEvents, 100, {
		'leading': true,
		'maxWait': 200,
		'trailing': true
	}));
}



/**
 * Handles the window scroll and uses a timeout to broadcast when stopped.
 */
function _scrollEvents() {

	// broadcast the scroll started
	wTop = $(window).scrollTop();

	$(window).trigger('Scroll/Start', [ wTop ]);

	// Broadcast if we're scrolled to the top
	if(wTop > 0) {
		if(!_previousScroll){
			$(window).trigger('Scroll/GoingDown', [ wTop ]);
		}

		// Broadcast scrolling direction
		if(_previousScroll) {
			if(_previousScroll > wTop){
				$(window).trigger('Scroll/GoingUp', [ wTop ]);
			} else {
				$(window).trigger('Scroll/GoingDown', [ wTop ]);
			}
		}
		_previousScroll = wTop;

		$(window).trigger('Scroll/Down', [ wTop ]);
	} else {
		$(window).trigger('Scroll/GoingUp', [ wTop ]);
		$(window).trigger('Scroll/Top', [ wTop ]);
	}

	// timeout to debounce
	clearTimeout(_scrollTimeout);

	// if timeout expires broadcast the scroll stop
	_scrollTimeout = setTimeout(function() {
		// Send top offset
		var wTop = $(window).scrollTop();
		$(window).trigger('Scroll/Stop', [ wTop ]);
	}, 100);
}



/**
 * Handles the resize events.
 */
function _resizeEvents() {

	// broadcast the scroll started
	$(window).trigger('Resize/Start');

	// timeout to debounce
	clearTimeout(_resizeTimeout);

	// if timeout expires broadcast the scroll stop
	_resizeTimeout = setTimeout(function() {
		$(window).trigger('Resize/Stop');
	}, 250);
}

module.exports = {
	init : init
};