F_checkbox.js 2.58 KB
/*
 * Select input typeof checkbox, and this function
 * work about father checkbox and son checkbox.
 * Code begin at 2015/05/27
 * By van
 */

define( 'F_checkbox' ,function( require, exports, module ){
  var F_checkbox = function( options ){
    var _this = this;
    _this.process = 0;

    var opt = $.extend( {
      name: {
        root: 'F_checkbox',
        father: 'fatherchk',
        son: 'childchk',
        target: 'input'
      }
    }, options );

    var name = opt.name;

    function _init(){
      //console.log( 'F_checkbox init...Ready!' )
      _click();
    };

    function _click(){
      _cl(name.root).find(name.target).on({
        click: _switch(_this.process)
      })
    }

    function _childAction(t){
      //console.log('child checkbox action.')
      _countChecked(t);
    };

    function _fatherAction(t){
      //console.log('father checkbox action.')
      _countChecked(t, true);
    };

    function _switch(){
      // var ev = Array.prototype.shift.call(arguments);
      var statu = arguments[0];

      switch(statu){
        case 0:
          return function(ev){
            var target = ev.target || ev.srcElement;
            var regexp = new RegExp(name.son);
            regexp.test(target.className) ? _childAction(target) : _fatherAction(target);
          }
          break;
        default:
          return function(){};
          break;
      }
    };

    function _countChecked(){
      var target = Array.prototype.shift.call(arguments);

      var brother = _cl(name.root, name.son);
      var c = [[]];

      for(var i=brother.length-1; i>=0; i--){
        brother[i].checked ? c[0].push(i) : c.push(i);
      };

      if (arguments[0]){
        if (target.checked){
          for (var i=c.length-1; i>=1; i--){
            brother[c[i]].checked = true;
          };
        }else {
          for (var i=c[0].length-1; i>=0; i--){
            brother[c[0][i]].checked = false;
          };
        }
      }else {
        _cl(name.father)[0].checked = (c[0].length == brother.length);
      }
    };

    /*
     * Loop the data and filter it whith fn. 
     * @param {function}
     * @retrun {}
     */
    function _filter(){
      try{

      }catch(e){};
    }

    /*
     * Adapt the id/class name with jquery.
     * @param {string}
     * @return {array}
     */
    function _id(n){
      return $("#"+ n);
    }
    function _cl(){
      var s = '', l = arguments.length;

      while(l){
        s += ' .' + Array.prototype.shift.call(arguments);
        l--;
      };

      return $(s);
    }

    return {
      init: _init
    }
  };

  return F_checkbox;
});