【问题标题】:jQuery plugin pattern using "live"使用“live”的 jQuery 插件模式
【发布时间】:2010-12-23 14:04:55
【问题描述】:

我有很多关于编写面向对象的javascript代码和开发jQuery插件的文章,到目前为止都很好,我了解它们是如何工作的,我可以创建自己的插件。

但是,所有文章都存在一个问题(即使有官方插件创作指南 - http://docs.jquery.com/Plugins/Authoring) - 这些所有模式都不支持“实时”。

让我们以这种模式为例 - http://www.virgentech.com/blog/2009/10/building-object-oriented-jquery-plugin.html

$.fn.myplugin = function(options)
{
   return this.each(function()
   {
       var element = $(this);

       // Return early if this element already has a plugin instance
       if (element.data('myplugin')) return;

       // pass options to plugin constructor
       var myplugin = new MyPlugin(this, options);

       // Store plugin object in this element's data
       element.data('myplugin', myplugin);
   });
};

将在每个 jQuery 匹配对象上创建新的“MyPlugin”实例。

如何更改它(如果可能的话),以便它适用于将来添加的元素?

谢谢

【问题讨论】:

  • 这些元素是如何添加的?
  • 它们可以使用 ajax 添加,我知道可以使用回调重新应用插件,但这似乎是一种浪费,因为将创建新对象

标签: jquery jquery-plugins live plugin-pattern


【解决方案1】:

我一直在我的插件中成功地使用 live 作为自定义选项。下面是一个简单的示例,它为被点击的元素添加警报:

$.fn.clickAlert = function(settings) {
    settings = $.extend({live: false}, settings);

    function clickAlertFn() {
        alert('Clicked!');
    }

    if (settings.live) {
        return this.live('click', clickAlertFn);
    } else {
        return this.click(clickAlertFn);
    }
};

// this will only work on existing `a` elements with class foo
$('a.foo').clickAlert();

// this will work on existing and future `a` elements with class bar
$('a.bar').clickAlert({live: true});

在这个例子中,任何可以正常使用 $('...').live('click', ...') 的东西都可以使用 $('...').clickAlert({live: true });

另外一件事,大多数插件设计都有你这样做:

$.fn.foo = function() {
    return $(this).each(function() {
        // code in here...
    });
}

很遗憾,在 each 循环内使用 live 不起作用。

【讨论】:

  • 1.你不需要包装this,因为它已经是 jQuery。 2. 代码更简单可以return this[settings.live ? 'live' : 'bind']('click', clickAlertFn);
  • 好点@Darcy!我更改了this,但保留了冗长的 if 语句以提高示例的可读性——但我确实喜欢这样的简化,并希望人们看到你的评论。
【解决方案2】:

我发现这很有效(jQuery 1.5.2):

(function($) {
$.fn.clickTest = function () {
    return this.each(function() {
        $('.clicker').die('click').live('click', function() {
            console.log('clicked');
        });
        $(this).click(function() {
            $('body').append('<a href="#" class="clicker">click here '+$(this).attr('id')+'</a><br> ');

        });
    });
}; }) (jQuery);

【讨论】:

    猜你喜欢
    • 2011-01-20
    • 1970-01-01
    • 1970-01-01
    • 2013-03-16
    • 2012-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-23
    相关资源
    最近更新 更多