jQuery.sub()


jQuery.sub()Returns: jQueryversion deprecated: 1.7, removed: 1.9

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

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

jQuery.sub() 的创建有两个特定的用例。第一个是提供一种轻松覆盖 jQuery 方法的方式,而不会完全破坏原始方法;另一个是帮助 jQuery 插件实现封装和基本命名空间。

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

请注意,如果您希望将此用于插件开发,则应首先强烈考虑使用类似 jQuery UI 小部件工厂(widget factory)的东西,该工厂可以管理状态和插件子方法。使用 jQuery UI 小部件工厂构建插件的一些示例

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

示例

示例 1

向 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

示例 2

覆盖一些 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'.

示例 3

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

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!
});