代码之家  ›  专栏  ›  技术社区  ›  Gelin Luo

jquery小部件,创建或初始化

  •  8
  • Gelin Luo  · 技术社区  · 15 年前

    一些jquery插件扩展小部件使用创建方法,而另一些则使用init方法,有人能解释这两者之间的区别吗?

    还有关于何时扩展小部件或直接扩展jquery.fn更好的指导吗?

    3 回复  |  直到 9 年前
        1
  •  5
  •   Ken Browning    15 年前

    扩展小部件(而不是$.fn)的缺点是,您创建了对jQueryUI的依赖关系,它定义了小部件“类”。对于不使用jquery ui的插件的用户来说,这种依赖性可能很昂贵。

    就create和init而言,我很确定init是第一个,然后在最近的一个修订版中,他们介绍并支持create。我可能错了,但我相信init仍然得到支持。如果是这样的话,那两者就不应该有任何区别。

        2
  •  18
  •   Mottie    15 年前

    jQuery UI Developer Guide :

    创建元素后,所有其他对小部件名称的调用(其中第一个参数不是字符串)都将调用_init()方法;如果传递了选项,则将在_init()方法之前调用.option()方法。

        3
  •  3
  •   CodingYoshi    9 年前

    小部件有三个阶段:

    +-------+----------------+---------------+--------------------------------------------------------------------------------------------+
    | Phase | Name           | jQuery Method | Description                                         |  
    +-------+----------------+---------------+--------------------------------------------------------------------------------------------+
    |     1 | Creation       | _create       | First time the widget is applied to an element, it is called.                              |  
    |     2 | Initialization | _int          | The _init method is called after _create when the widget is first applied to its elements. |  
    |     3 | Destruction    | destroy       | The widget's destroy method is used to detach a widget from an element.                    |  
    +-------+----------------+---------------+--------------------------------------------------------------------------------------------+
    

    注释 :根据约定,以下划线开头的方法名称是私有的。


    所以两者之间有区别 _create _init . 一个用于创建,另一个用于初始化。每次调用没有参数或选项的小部件时,它都会间接调用 输入输出 方法。因此,这可以用来 重置 (重新初始化)一个小部件或传递不同的选项。

    有关每个阶段的详细信息 here .