simulate.js 1.98 KB
/*
 * Simulate the input["checbox" || "radio"];
 * Recode in 2015/07/16
 * By van
 */

define( 'simulate' ,function( require, exports, module ){
  var simulate = function(target, options){
    var opt = $.extend({
      'target': 'input',
      'tpl': {
        'chk': '<i class="ic s-chk"></i>',
        'rdo': '<i class="ic s-rdo"></i>'
      },
      'open': 'Simuopen' 
    }, options);

    //Cache some long varialbe name.
    var tpl = opt.tpl, op = opt.open;
    var doms = {};

    //Pack every node in target.
    _each(target, function(tag){
      _pkgroom(tag);
    });

    //As the input.name different, the clickTarget is defferent.
    _each(doms, function(dom_each){
      _each(dom_each, function(de, des){
        //Bound ClickEvent For change the checked display. 
        $(de).on({
          click: function(){
            _this = this;
            _each(des, function(_d){
              _d != _this || !_this.checked ?  $(_d).parent().removeClass(op) : $(_this).parent().addClass(op);
            });
          }
        })
      })
    }, 'O');

    /*
     * Loop a unit which is [array] or {object}
     * And run a callback to do something.
     * @parem {Array/Object, function, string}
     * @return {Array/Object}
     */
    function _each(arr, fn, type){
      switch(type){
        case 'O':
          for (var each in arr){
            fn(arr[each], arr);
          };
          break;
        default:
          for (var i = 0, l = arr.length; i < l; i++){
            fn(arr[i], arr);
          };
      };

      return arr;
    };

    /*
     * Distinguish the input and pack different html package.
     * Only two type ['radio', 'checkbox'].
     * @param {HTMLDOM}
     * @return 
     */
    function _pkgroom(target){
      var inp = $(target).find(opt.target)[0];
      inp && inp.type == 'radio' ? $(inp).after(tpl.rdo) : $(inp).after(tpl.chk);

      var name = inp.name;
      doms[name] != null ? doms[name].push(inp) : doms[name] = [inp];
    };
  };
  
  return simulate;
});