checkbox.js 2.49 KB
/**
 * Checkbox组件
 * 使用: 
 * 1. 多选多或一选一 $(selector).checkbox()
 * 2. 多选一 需要为父元素添加'multi-checkbox'的class  $(selector).checkbox()
 * 3. 为checkbox添加data-checkbox='false', 该checkbox将不会初始化为Checkbox组件
 */
define('checkbox', ['components/common', 'jquery'], function() {
    var labelTmp = "<label class='checkbox-inner'></label>";
    var defaultSettings = {
        onClick: function () { }
    };
    var Checkbox = function(ele, settings) {
        var $checkbox = $(ele),
            id = ele.id;

        settings = $.extend({}, defaultSettings, settings);

        if($checkbox.next(".checkbox-inner").length) return; // 防止重复调用
        if($checkbox.attr("data-checkbox") == 'false') return; // 防止与其他同类型组件冲突

        if(!id) {
            id = 'checkbox'+Checkbox.index++;
            $checkbox.attr('id', id);
        }

        $checkbox.addClass("checkbox");
        $checkbox[0]._onclick = settings.onClick;
        $checkbox.parent().addClass("checkbox-wrapper");

        $(labelTmp).insertAfter($checkbox).attr("for", id);
    };

    Checkbox.index = 0;

    $("body").on("click.singleCheckbox", ".multi-checkbox .checkbox-inner", function() {
        var $checkbox = $(this),
            $checkboxWrapper = $checkbox.parents(".multi-checkbox");
        
        $checkboxWrapper.find(".checkbox").each(function() {
            $(this).prop("checked", false);
        });

        $checkbox = $checkbox.siblings(".checkbox").trigger("click");

        setTimeout(function() {
            $checkbox.prop("checked", true);
            $checkbox[0]._onclick();
        });
    }).on("click.oneCheckbox", ":not(.multi-checkbox)>.checkbox-wrapper .checkbox-inner", function(){
        var $checkbox = $(this).siblings(".checkbox");
        setTimeout(function () {
            $checkbox[0]._onclick();
        });
    });

    $.fn.checkbox = function(settings) {
        var $el = $(this);

        if($el.attr("type") == "checkbox") {
            new Checkbox(this, settings);
        } else {
            $el.find("input[type=checkbox]").each(function() {
                new Checkbox(this, settings);
            });
        }

        return $el;
    };

    $.fn.checked = function(unchecked) {
        var $el = $(this);
        
        setTimeout(function() {
            if (unchecked) return $el.removeProp("checked");
            
            $el.prop("checked", "checked").triggerHandler("click");
        }, 50);
    };
});