jQuery.sub()


jQuery.sub()返回值: jQuery版本弃用: 1.7, 版本移除: 1.9

描述: 创建一个新的 jQuery 副本,其属性和方法可以修改,而不会影响原始 jQuery 对象。

注意: 此 API 已在 jQuery 1.9 中移除。

jQuery.sub() 的创建是为了解决两个特定的用例。第一个是提供一种无痛的方式来覆盖 jQuery 方法,而不会完全破坏原始方法,另一个是帮助对 jQuery 插件进行封装和基本命名空间。

请注意,jQuery.sub() 不会尝试进行任何形式的隔离 - 这不是它的目的。子版本 jQuery 上的所有方法仍然指向原始 jQuery(绑定和触发的事件仍然通过主 jQuery 进行,数据仍然通过主 jQuery 绑定到元素,Ajax 查询和事件仍然通过主 jQuery 运行,等等)。

请注意,如果您想将此方法用于插件开发,您应该首先强烈考虑使用 jQuery UI 小部件工厂之类的工具,它可以管理状态和插件子方法。 使用 jQuery UI 小部件工厂构建插件的一些示例

此方法的特定用例可以通过一些示例来最好地描述。

示例

向 jQuery 子类添加一个方法,使其不会在外部暴露。

1
2
3
4
5
6
7
8
9
10
11
12
(function(){
var sub$ = jQuery.sub();
sub$.fn.myCustomMethod = function() {
return "just for me";
};
sub$( document ).ready(function() {
sub$( "body" ).myCustomMethod() // "just for me"
});
})();
typeof jQuery( "body" ).myCustomMethod // undefined

覆盖一些 jQuery 方法以提供新的功能。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
(function() {
var myjQuery = jQuery.sub();
myjQuery.fn.remove = function() {
// New functionality: Trigger a remove event
this.trigger( "remove" );
// Be sure to call the original jQuery remove method
return jQuery.fn.remove.apply( this, arguments );
};
myjQuery(function( $ ) {
$( ".menu" ).on( "click", function() {
$( this ).find( ".submenu" ).remove();
});
// A new remove event is now triggered from this copy of jQuery
$( document ).on( "remove", function( event ) {
$( event.target ).parent().hide();
});
});
})();
// Regular jQuery doesn't trigger a remove event when removing an element
// This functionality is only contained within the modified 'myjQuery'.

创建一个返回插件特定方法的插件。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
(function() {
// Create a new copy of jQuery using sub()
var plugin = jQuery.sub();
// Extend that copy with the new plugin methods
plugin.fn.extend({
open: function() {
return this.show();
},
close: function() {
return this.hide();
}
});
// Add our plugin to the original jQuery
jQuery.fn.myplugin = function() {
this.addClass( "plugin" );
// Make sure our plugin returns our special plugin version of jQuery
return plugin( this );
};
})();
$( document ).ready(function() {
// Call the plugin, open method now exists
$( "#main" ).myplugin().open();
// Note: Calling just $( "#main" ).open() won't work as open doesn't exist!
});