2011-09-02 77 views
-1

所以我认为这应该是非常简单的...它只是一个自定义复选框插件,需要使用div,并将它们变成使用css的复选框。我真正需要的是基本上交换CSS和触发事件。我只看到需要这些操作(init,check,uncheck,toggle,disable)。 继承人任何方式我有什么,到目前为止,但IM卡上的切换方法和一般的最后一部分...第一个jQuery插件,我在正确的轨道上?

(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); 

我是朝着正确的方向或者我应该完全不同的打算这件事?

+0

迁移到代码审查? – Neal

+0

http://codereview.stackexchange.com/ - 但不幸的是,它似乎太旧 – Alexander

回答

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; 
} 
0

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

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

你会调用插件的方法,每个人都以同样的方式都这么做:

this.customCheckbox("check"); 
+0

ummm不会做'$(this).customCheckbox(“check”);'? – Neal

+0

@Neal:只在“每个”中。 – SLaks

0

使用此

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

'arguments'不是一个数组,也没有'slice'方法。 – SLaks

+0

@Slaks - 是的你说得对,现在好吗? – ShankarSangoli

+0

不是。这可能工作,但它滥用jQuery, – SLaks