【问题标题】:What is a way to make JQuery plugin extendible?什么是使 JQuery 插件可扩展的方法?
【发布时间】:2013-03-01 14:33:55
【问题描述】:

我尝试通过以下方式将一些常见的应用程序特定操作移动到 jQuery 插件

$.fn.extpoint = function() {...}

但我不想声明几个扩展点:

$.fn.extpoint1 = function() {...}
$.fn.extpoint2 = function() {...}
...

相反,我想使用如下语法糖:

$("#id").extpoint.func1().extpoint.func2()

有定义:

$.fn.extpoint = {}
$.fn.extpoint.func1 = function() {
    this.val();
    this.data("ip");
    ...
    return this;
}

然后调用:

$("#id").extpoint.func1(...)

this 指向 $.fn.extpoint(带有 func1func2、... 元素的字典)而不是原始 jQuery 对象,当 func1 评估时。

jQuery插件可以扩展吗?

附言。可以将函数名称作为第一个参数传递给$.fn.extpoint 并实现$.fn.extpoint('extend', func) 调用以扩展(保存到名称和实现之间的内部字典关联)扩展点。在这种情况下,用例如下所示:

$("#id").extpoint('func1', ...).extpoint('func2', ...)

但我正在寻找更多语法的方法 sugar...

【问题讨论】:

  • 这样不行:$("#id").extpoint.func1().extpoint.func2() 因为 func1 和 func2 无法访问$("#id")
  • @KevinB 是的,我明白了,但是想办法用一些未知的技巧来避免这种情况...... +1
  • 一两年前在 jQuery 论坛上有一个帖子,有人想出了一种方法来实现这一点,但它非常复杂,我不记得它是如何完成的。我建议在那里搜索它,我找不到它。
  • 好像我找到了你提到的线程:groups.google.com/group/jquery-dev/browse_thread/thread/…

标签: javascript jquery jquery-plugins plugins syntactic-sugar


【解决方案1】:

Here 是创建插件的概述。我相信你所问的是所谓的“链接”。这就是让 jQuery 如此易于使用的原因,而且您希望确保正确地实现它是一件好事。

在开发有关链接的插件时要记住的关键是始终从您的方法中使用return this;。这样才能让链条保持运转。

【讨论】:

  • 对不起,我不谈论链接。但是关于使 jQuery 插件 以某种与 jQuery 本身一致的方式可扩展...
【解决方案2】:

我提出的任务很难实现。

Official docs说:

在任何情况下,单个插件都不应在 jQuery.fn 对象中声明多个命名空间

(function( $ ){
  $.fn.tooltip = function( options ) { 
    // THIS
  };
  $.fn.tooltipShow = function( ) {
   // IS
  };
  $.fn.tooltipHide = function( ) { 
    // BAD
  };
})( jQuery );

不鼓励这样做,因为它会混淆 $.fn 命名空间。为了解决这个问题,您应该将插件的所有方法收集在一个对象字面量中,并通过将方法的字符串名称传递给插件来调用它们。

另一种方法是保持与this 的链接,如http://code.google.com/p/jquery-plugin-dev/source/browse/trunk/jquery.plugin.js 中一样

所以你的电话看起来像:

$.fn.addPlugin('test2', {
    __construct : function(alertText) { alert(alertText); },
    alertAttr   : function(attr) { alert($(this).attr(attr)); return this; },
    alertText   : function() { alert($(this).text()); return this; }
});

$('#test2').bind('click', function() {
     var btn = $(this);

     btn.test2('constructing...').alertAttr('id').alertText().jQuery.text('clicked!');

     setTimeout(function() {
             btn.text('test2');
     }, 1000);
});

一些相关链接:

旧式插件扩展:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    • 2011-01-04
    相关资源
    最近更新 更多