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

向插件添加回调和触发事件

  •  3
  • Mottie  · 技术社区  · 14 年前

    我已经将回调和触发事件添加到插件中,如下所示:

    // located at the point where the event and callback should be called
    el.trigger('initialized', el);
    if ($.isFunction(options.onInitialize)) { options.onInitialize(el); }
    

    但我发现了另一种方法,它是这样做的:

    // located at the beginning of the script, after the options are extended
    if ($.isFunction(options.onInitialize)) { el.bind('initialized', options.onInitialize; }
    
    // located at the point where the event should be called
    el.trigger('initialized', el);
    

    所以,我的问题是,事件是在第一个方法的回调之前触发的,还是我应该切换到使用第二个方法,在这两个方法同时发生的情况下,使用第二个方法?

    更新:到目前为止,我唯一想到的原因是最小化函数调用- $.isFunction 在第二个示例中只调用一次。

    1 回复  |  直到 14 年前
        1
  •  0
  •   Mottie    14 年前

    最后我采用了第二种方法。自从 $.isFunction() 被称为每个周期,似乎只做一次更有效。我也可以缓存结果…所以我想这两种方法都可以。