代码之家  ›  专栏  ›  技术社区  ›  Mickel

使调用自定义jquery插件更容易

  •  0
  • Mickel  · 技术社区  · 15 年前

    我写了一个带有以下“签名”的插件:

    jQuery.fn.attach = function(element, settings, duration, options, callback) {
    

    在这里 element 是jquery对象, settings 是我的插件的自定义设置和 duration , options callback 是我在jquery的animate中使用的所有参数,如下所示:

    someObject.animate({ someCSS }, duration, options, callback);
    

    现在,我的问题是:是否可以使这个函数更容易调用?例如,现在,让一切按我的期望工作…我必须包含所有参数并设置不使用的参数 null :

    $(this).attach($('#e1-blue'), null, 3000, null, function() { alert('done'); });
    

    很高兴 可以将其称为:

    $(this).attach($('#e1-blue'), 3000, function() { alert('done'); });
    

    因此(OFC)

    $(this).attach($('#e1-blue'), 3000);
    

    有什么建议吗?

    3 回复  |  直到 15 年前
        1
  •  1
  •   Karl B    15 年前

    我能想到的最简单的事情就是重新排序参数,这样最常用的参数就会排在第一位。因此,如果将函数更改为:

    jQuery.fn.attach = function(element, duration, callback, settings, options) {
    

    然后,通过将默认值放入函数体,可以使所有内容(可能是第一个参数除外)都成为可选的。例如:

    if(!duration)
       duration = 3000;
    

    然后

    $(this).attach($('#e1-blue'), 3000, function() { alert('done'); });
    

    $(this).attach($('#e1-blue'), 3000);
    

    两者都有效,其他值自动填充为 null .

    严格来说,您可以检查函数中的参数类型,例如,如果第二个参数是整数,那么它是 duration ,如果它是一个函数, callback 如果它是一个物体 settings 但我不认为以后必须遵循您的代码的人会为此感谢您。如果需要第二个整型参数,这也会使函数很难在后面的行中扩展。

        2
  •  2
  •   czarchaic    15 年前

    我设置了一个默认对象,在插件函数中只接受一个参数。

      $.fn.myPlugin=function(opt){
        var o=$.extend({}, $.fn.myPlugin.defaults, opt||{});
      };
      $.fn.myPlugin.defaults={
        element: null,
        settings: null,
        options: null,
        callback: null,
        duration: 250
      };
    

    实例化插件

    $('#myElement').myPlugin({element: $('#el-blue'), duration: 2000})
    

    如果每次都传递一些内容,可以使选项对象成为第二个参数。

      $.fn.myPlugin=function(element, opt){
       return this.each(function(){
        var o=$.extend({}, $.fn.myPlugin.defaults, opt||{});
        //do some stuff
        if (o.callback) {
         o.callback.call(this, o);
        }
       });
      };
    
    $('#myElement').myPlugin($('#el-blue'), {duration: 3000, callback: function(){}});
    
        3
  •  0
  •   BBonifield    15 年前

    我建议您查看方法签名以了解人们如何处理可选参数。例如,看看 http://gist.github.com/277432#LID5445 要查看jquery.speed后面的设置,jquery.animate使用的就是它- 网址:http://gist.github.com/277432 lid5445 .

    不管怎样,你只想看看你的论点的类型,看看是否有人把它们传了进来。