12/03/15 10:35:54 E:\Projects\jslib\js\lib\throttle.js
  1 
/**
  2 
* @module lib/throttle
  3 
*/
  4 
define(
  5 
    [],
  6 
    function() {
  7 
        /**
  8 
         *
  9 
         */
 10 
        function throttle(target, eventName, throttledEventName, options) {
 11 
            switch (options.type) {
 12 
                case "animation":
 13 
                    animationThrottle(target, eventName, throttledEventName, options);
 14 
                    break;
 15 
 
 16 
                default:
 17 
                    defaultThrottle(target, eventName, throttledEventName, options);
 18 
            }
 19 
        }
 20 
 
 21 
 
 22 
        /**
 23 
         *
 24 
         */
 25 
        function animationThrottle(target, eventName, throttledEventName, options) {
 26 
            if (!window.requestAnimationFrame) {
 27 
                defaultThrottle(target, eventName, throttledEventName);
 28 
            } else {
 29 
                var running = false;
 30 
                var onFrame = function() {
 31 
                    target.dispatchEvent(new CustomEvent(throttledEventName));
 32 
                    running = false;
 33 
                };
 34 
                var onEvent = function() {
 35 
                    if (!running) {
 36 
                        running = true;
 37 
                        requestAnimationFrame(onFrame);
 38 
                    }
 39 
                };
 40 
                target.addEventListener(eventName, onEvent);
 41 
            }
 42 
        }
 43 
 
 44 
 
 45 
        /**
 46 
         *
 47 
         */
 48 
        function defaultThrottle(target, eventName, throttledEventName, options) {
 49 
            var running = false;
 50 
            var onTimeout = function() {
 51 
                target.dispatchEvent(new CustomEvent(throttledEventName));
 52 
                running = false;
 53 
            };
 54 
            var onEvent = function() {
 55 
                if (!running) {
 56 
                    running = true;
 57 
                    setTimeout(onTimeout, options.delay || 100);
 58 
                }
 59 
            }
 60 
            target.addEventListener(eventName, onEvent);
 61 
        }
 62 
 
 63 
 
 64 
        /* Provides function throttle. */
 65 
        return throttle;
 66 
    }
 67 
);