movemove.js 2.35 KB
define(function(require, exports, module) {

var movemove = function(target, options){
  var opt = $.extend({
    name: {
      box: 'listbox',
      inner: 'ul',
      child: 'li'
    },
    moveType: 2,
    interval: 3000
  }, options);

  var ne = opt.name, clock, animate;

  function _init(){
    var doms  = getDoms();
    var cache = [_shiftArray(doms.li, 2), doms.li];

    //If the childnode's number less than six, we stop the action.
    if (cache[1].length < 6)return false;
    opt.moveType == 1 ? animate = _anone : animate = _antwo;
    animate( doms, cache );
  };

  function _anone( doms, cache ){
    clock = setInterval(function(){
      doms.ul.animate(
        {'top': -$(doms.li).height()},
        300,
        function(){
          $(this).removeAttr('style');
          for (var i = 0, l = cache.length; i < l; i++){
            $(cache[0][i]).remove().appendTo($(this));
          }
          cache = _change(cache);
        }
      );
    }, opt.interval);
  };

  function _antwo( doms, cache ){
    var t = 0;

    clock = setInterval(function(){
      doms.ul.css({
        'top': t-=1
      });
      if (t == -30){
        doms.ul.removeAttr('style');
        t = 0;
        for (var i = 0, l = cache.length; i < l; i++){
          $(cache[0][i]).remove().appendTo(doms.ul);
        }
        cache = _change(cache);
      }
    }, 50);
  };
  
  function _clear(){
    clearInterval( clock );
  };

  function getDoms(){
    var box = $('.'+ ne.box);

    return {
      box: box,
      ul : box.find(ne.inner),
      li : box.find(ne.child)
    }
  };

  /*
   * Slice the Array with the param(shiftNumber),
   * And return an array with shiftNumber length;
   * @param {array, number}
   * @return {array}
   */
  function _shiftArray(array, shiftNumber){
    var cache = [];
    for ( var i = 0; i < shiftNumber; i++ ){
      cache.push( _shift(array) );
    };
    return cache;
  };

  /*
   * @param {array([],[])}
   * @return {variable}
   */
  function _change(arr){
    for ( var i = 0, l = arr[0].length; i < l; i++ ){
      _push( arr[0], _shift(arr[1]) );
      _push( arr[1], _shift(arr[0]) );
    };
    return arr;
  };

  function _shift(arr){
    return Array.prototype.shift.call(arr);
  };

  function _push(arr, elem){
    return Array.prototype.push.call(arr, elem);
  };

  return {
    init: _init,
    clear: _clear
  }
};

return movemove;

});