2

我尝试通过以下方式将一些常见的应用程序特定操作移动到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字典)而不是原始 jQuery 对象。func1func2func1

是否可以使 jQuery 插件可扩展?

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

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

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

4

2 回答 2

2

我提出的任务很难实施。

官方文档说:

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

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

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

另一种方法是保持链接thishttp://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);
});

一些相关链接:

旧式插件扩展:

于 2013-03-13T22:01:19.613 回答
1

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

在开发有关链接的插件时要记住的关键是始终return this;使用您的方法。这就是让你保持链条运转的原因。

于 2013-03-13T15:15:21.897 回答