我尝试通过以下方式将一些常见的应用程序特定操作移动到 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
(带有 func1
、func2
、... 元素的字典) 而不是原始的 jQuery 对象,当 func1
求值时。
是否可以使 jQuery 插件可扩展?
附注。可以将函数名称作为第一个参数传递给 $.fn.extpoint
并实现 $.fn.extpoint('extend', func)
调用来扩展(保存到名称和实现之间的内部字典关联)扩展点。在这种情况下,用例看起来像:
$("#id").extpoint('func1', ...).extpoint('func2', ...)
但我正在寻找方法来制作更具语法性的糖...
最佳答案
我提出的任务很难实现。
在任何情况下,单个插件都不应在 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);
});
一些相关链接:
- http://milan.adamovsky.com/2010/02/how-to-write-advanced-jquery-plugins.html
- http://milan.adamovsky.com/2010/09/jquery-plugin-pattern-20.html
- http://ludw.se/blog/articles/19/patching-milans-jquery-plugin-pattern-for-jquery-16
- http://code.google.com/p/jquery-plugin-dev/source/browse/trunk/jquery.plugin.js
旧式插件扩展:
关于javascript - 有什么方法可以使 JQuery 插件可扩展?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15389025/