【问题标题】:How to create a jQuery plugin with a first time initialization?如何创建一个第一次初始化的 jQuery 插件?
【发布时间】:2012-03-19 15:29:56
【问题描述】:

我正在创建一个 jQuery 插件,它在第一次被调用时需要做很多事情(而且只是第一次)。我第一次需要从 dom 的一部分构建索引时,我只想这样做一次,然后在其余时间使用该索引。

理想情况下,我希望它像这样工作:

  1. 第一次调用时,设置运行函数 init() 并设置我在整个插件中需要的所有大量 var(所以我不能在 init() 中定义它们,因为它们在其余部分不可用插件)。
  2. 所有其他调用它的时候都应该使用第一次定义的变量。

首先我尝试了这个:

  $.fn.search = function() {  

    if( !inited ) {
    /*
        Define everything that should only be defined the first time
    */
    }

    /*
        All methods for my plugin, including an init() method
    */

    if( !inited ) {
        init();
        var inited = true;
    } 

 };

但我发现每次调用插件时所有变量都消失了,所以这不起作用。我知道我可以像这样存储东西:

$.fn.search.config = {
    inited = false,
    output,
    search,
    singleElems,
    templates,
    included,
    scoreBoard,
    container,
    singles
}

并在 init() 中定义它们,但这是为插件存储内容的最佳方式吗?

【问题讨论】:

    标签: jquery plugins init


    【解决方案1】:

    使用data,这是大多数插件用来存储状态和避免重复初始化的方式:

    $.fn.search = function() {
        return this.each(function() { // For each selected element
            var data = $(this).data("search");
            if ( !data ) {
                var state = {};
                // Your plugin logic
                $(this).data("search",state);
            }
        });
    };
    

    【讨论】:

    • 就是这样,谢谢!请注意,闭包中的this 已经是一个jQuery 对象,因此您可以只使用this 而不是$(this)(对吗?)
    • 是的,但请记住,它是一个对象集合,包含零个、一个或多个元素。为了安全起见,请使用return this.each(function() { ... }); 并将您的代码放入该函数中(在这种情况下,this 不是 jQuery 对象,而是一个元素,因此您可能必须使用 $(this)
    【解决方案2】:

    您可以使用.data('myPluginData',{a:b,c:d}) (docs) 将您需要的所有设置存储在附加到应用插件的元素的单个命名空间对象中。数据部分见:http://docs.jquery.com/Plugins/Authoring#Data,方法调用逻辑见http://docs.jquery.com/Plugins/Authoring#Plugin_Methods

    通过这种方式,您可以轻松跟踪使用的设置并使用 if ($(this).data('myPluginData')) 之类的东西来确定插件是否已在任何给定对象上调用,然后只需使用 $(this).data('myPluginData').settingA 之类的东西来访问存储的设置。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-24
      • 1970-01-01
      • 2018-04-07
      • 2014-06-07
      • 1970-01-01
      • 2018-06-06
      • 1970-01-01
      相关资源
      最近更新 更多