第一个jQuery插件,我是在正确的轨道上吗?

时间:2011-09-02 16:02:50

标签: javascript jquery jquery-plugins

所以我认为这应该非常简单......它只是一个自定义的Checkbox插件,它使用div并使用css将它们变成复选框。我真正需要做的就是交换css和触发事件。我只看到需要这些动作(init,check,uncheck,toggle,disable)。 到目前为止,我所拥有的任何方式,但我坚持切换方法和最后一部分......

(function ($) {
    var method = {
        init: function () {
            $(this).addClass('cb-unchecked');
            $(this).click(//Should call toggle method, but unsure syntax);
        },

        check: function () {
            return this.each(function () {
                $(this).removeClass('cb-disabled cb-unchecked').addClass('cb-checked').trigger('checked', this);
            });
        },

        uncheck: function () {
            return this.each(function () {
                $(this).removeClass('cb-disabled cb-checked').addClass('cb-checked').trigger('unchecked', this);
            });
        },

        toggle: function () {
            return this.each(function () {
                var t = $(this);
                if (t.hasClass('cb-checked')) { //Should call the check function, but i dont know how...  }
                else if (t.hasClass('cb-unchecked')) { //Should call the uncheck function, but i dont know how...}
            });
        },

        disable: function () {
            return this.each(function () {
                $(this).removeClass('cb-checked cb-unchecked').addClass('cb-disabled').trigger('disabled', this);
            });
        }

    };
    $.fn.customCheckbox = function (action) {

        //Im slightly lost at what would go here
        //if(method[action]){ method[action].apply(this, arguments);  }//????

        return this;
    }
})(jQuery);

我是朝着正确的方向前进还是应该以完全不同的方式解决这个问题?

3 个答案:

答案 0 :(得分:1)

是的,你走在正确的轨道上。你将它包装在(function($){..})(jQuery)中,让jQuery与其他javascript库很好地配合。您可以通过return this;维护可链接性。您可以使用$.fn.customCheckbox = ...正确扩展jQuery。您可以通过将参数应用于函数来执行注释。最后,请打电话。

$("input[type='checkbox']").customCheckbox('init');

虽然我可能会在$.fn.customCheckbox = function (action) {...}

时将初始化代码移到!action的正文中
$.fn.customCheckbox = function (action) {
        if(!action){
            // init here
        }
        // other logic here
        return this;
}

答案 1 :(得分:0)

评论中的代码几乎是正确的 但是,您需要在调用方法之前删除第一个参数(action):

method[action].apply(this, Array.prototype.slice.call(arguments, 1));  

您可以像其他人一样调用插件方法:

this.customCheckbox("check");

答案 2 :(得分:0)

使用此

$.fn.customCheckbox = function (action) {
        if(action && method[action]){ 
           var args = arguments;
           args = $(args).slice(1);
           method[action].apply(this, args);  
        }
        return this;
}