【问题标题】:Make it easier to call a custom jQuery plugin让调用自定义 jQuery 插件更容易
【发布时间】:2010-01-21 17:15:40
【问题描述】:

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

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

这里element是一个jQuery对象,settings是我的插件的自定义设置,durationoptionscallback都是我在jQuery动画中使用的参数,像这样:

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

有什么建议吗?

【问题讨论】:

    标签: javascript jquery plugins jquery-plugins


    【解决方案1】:

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

      $.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(){}});
    

    【讨论】:

      【解决方案2】:

      我能想到的最简单的事情是重新排序参数,以便最常用的参数排在第一位。因此,如果您将功能更改为:

      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,但我不认为以后必须遵循你的代码的人会感谢你它。如果例如,它还可能使功能难以在以后扩展需要第二个整数参数。

      【讨论】:

        【解决方案3】:

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

        无论如何,你只想看看你的论点的类型,看看人们是否传递了它们。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-01-06
          • 1970-01-01
          • 1970-01-01
          • 2011-05-15
          • 1970-01-01
          相关资源
          最近更新 更多