【问题标题】:Function calls inside jQuery pluginjQuery插件内部的函数调用
【发布时间】:2013-12-22 09:41:00
【问题描述】:

我几乎有这个定义插件实例的代码:

$.fn.someplugin = function(opts) {
  $(document).on('click', '.option-1', function() {
    alert(1);
  });
};

我使用一些类似这样的代码来使我的插件工作:

$('.selector-1').someplugin();

所以 jQuery 以这种方式将可能的单击事件侦听器绑定到文档。

问题是,当我多次使用我的插件时,是否意味着jQuery绑定了10个点击事件到文档?

$('.selector-1').someplugin();
$('.selector-2').someplugin();
$('.selector-3').someplugin();
$('.selector-4').someplugin();
$('.selector-5').someplugin();
$('.selector-6').someplugin();
$('.selector-7').someplugin();
$('.selector-8').someplugin();
$('.selector-9').someplugin();
$('.selector-10').someplugin();

通过这种方式,它绑定了 10 个点击监听器 - 因为 fn.someplugin 被调用了 10 次,还是只调用了一次?

【问题讨论】:

    标签: javascript jquery html events plugins


    【解决方案1】:

    是的,它将 10 个点击侦听器绑定到 $(document) 对象。

    每次调用someplugin() 都会绑定一个新的监听器。

    JSFIDDLE


    如果您想向文档(在您的插件内部)添加单击处理程序,您可以这样做:

    (function ($) {
        $.fn.someplugin = function(opts) {
           alert("Another someplugin call.");
        };
    
        $(document).on('click', '.option-1', function() {
           alert(1);
        });
    })($);
    

    JSFIDDLE

    【讨论】:

    • 该死的,真的很糟糕。
    • @Steve 为什么它真的很糟糕?你期待什么?
    • 我想最小化事件处理程序,因为我的页面上可能有超过 200 个插件调用。然后性能开始下降。
    • @Steve 这取决于你的插件是如何工作的。查看我的编辑。
    【解决方案2】:

    你可以这样做只绑定一次:

    (function ($) {
        $.fn.someplugin = function (opts) {
            return $(this).each(function (index, value) {
                $(document)
                .off('click', '.option-1')
                .on('click', '.option-1', function (event) {
                    event.preventDefault();
                    alert(1);
                });
            });
        };
    })(jQuery);
    
    $(document).ready(function () {
        $('.selector-1, .selector-2').someplugin();
    });
    

    $(this).each 允许您绑定多个选择器。

    .off() 取消绑定事件(如果存在)。

    jsfiddle: http://jsfiddle.net/rWYS4/

    【讨论】:

    • 我认为事件监听器应该移到插件实例之外,但在匿名函数内部。你的例子很好,但它不是一个性能友好的例子。
    • 是的。插件函数“应该”只绑定选项选择器上的事件,而不是全局选择器。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-01
    • 1970-01-01
    • 2014-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多