Примеры для jQuery.sub()


Adding a method to a jQuery sub so that it isn't exposed externally:

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

Override some jQuery methods to provide new functionality.

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" ).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'.

Create a plugin that returns plugin-specific methods.

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