概述 jQuery.sub()
返回值:jQuery
描述:可创建一个新的jQuery副本,其属性和方法可以修改,而不会影响原来的jQuery对象。
这种方法在jQuery1.7已经被过时了,在jQuery 1.8版本将被移动到一个插件中。
有两个具体使用jQuery.sub()创建jQuery副本的案例。第一种情况是希望重写 jQuery 的方法,而不想破坏原始的方法。另一种情况是想为 jQuery 插件做进一步的封装或进行基本的命名空间。
注意,jQuery.sub() 并不尝试做任何形式的隔离,因为这不是该方法的本意。所有 jQuery 副本中的方法依然指向原始的 jQuery (例如,依然会通过原始的 jQuery 进行事件绑定和触发,data 也会通过原始的 jQuery 绑定到元素上。Ajax 请求和事件也是通过原始的 jQuery 运行的等等。)。
请注意,如果你正在寻找使用这个开发插件,应首先认真考虑使用一些类似jQuery UI widget工厂,这两个状态和插件管理子方法。 使用jQuery UI widget的一些示例建立一个插件。
上述那些示例非常好的描述了该方法的详细用法。
示例
添加一个jQuery的方法,以便它不会受到外部分:
- (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 方法,提供新的功能。
- (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").click(function() {
- $(this).find(".submenu").remove();
- });
-
- // A new remove event is now triggered from this copy of jQuery
- $(document).bind("remove", function(e) {
- $(e.target).parent().hide();
- });
- });
- })();
-
- // Regular jQuery doesn't trigger a remove event when removing an element
- // This functionality is only contained within the modified 'myjQuery'.
创建一个插件,返回插件的具体方法。
- (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!
- });