【问题标题】:Authoring plugins jQuery documentation编写插件 jQuery 文档
【发布时间】:2018-02-28 09:59:01
【问题描述】:

我正在玩弄一些创作插件,所以我转向了 jQuery 文档,其中讨论了不要弄乱 $.fn 对象,以及没有一个插件应该超过 $.fn 命名空间...

(function( $ ){

  var methods = {
    init : function( options ) { 
      // THIS 
   },
    show : function( ) {
      // IS
    },
    hide : function( ) { 
      // GOOD
    },
    update : function( content ) { 
      // !!! 
    }
  };

  $.fn.tooltip = function( method ) {

    // Method calling logic
    if ( methods[method] ) {
      return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
    } else if ( typeof method === 'object' || ! method ) {
  return methods.init.apply( this, arguments );
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.tooltip' );
    }    

  };

})( jQuery );

// calls the init method
$('div').tooltip(); 

// calls the init method
$('div').tooltip({
  foo : 'bar'
});

直到:

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

部分。

我把那一点改成了简单的:

$.fn.tooltip = function(method)
{
    if(myFunc[method])
    {
        return myFunc[method].apply();
    }
}

它工作得很好......有人可以向我解释一下那里发生了什么以及为什么我的工作似乎很好吗?

编辑:顺便说一句,我知道我没有完全继续 if/else 结构,那是因为我完全专注于我提到的那一行,而不是 if 结构的其余部分。

【问题讨论】:

  • 你的方式假设你的“方法”都不需要额外的参数。如果它们需要其他参数,则需要添加它们。您甚至可以将其进一步简化为 return myFunc[method]()
  • 你能再详细点吗?也许给出了一个我如何添加其他参数的例子?真的,我只是想了解 jQuery 的文档示例发生了什么。
  • 例如,如果你的插件有一个“跳转”方法,你会想给它一个“高度”参数。 $(el).myPlugin("jump","3ft")。如果您从原始代码中删除所有多余的东西,您将无法将 "3ft" 部分传递给该方法。
  • 啊,它刚刚点击,谢谢!如果你构建了这个主题的答案,我会继续检查它。

标签: jquery plugins


【解决方案1】:

您的操作方式很好,但是,它不允许您将任何参数传递给您的方法。

例如,如果您的插件有一个 option 方法允许您更改工具提示文本选项,您可以这样调用它:

$(element).tooltip("option","text","foobar!!");

如果您删除所有其他代码并使用您的方式执行此操作,option 方法将不会收到 "text""foobar!!!" 参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-13
    • 2014-09-14
    • 1970-01-01
    相关资源
    最近更新 更多