Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I don't understand the new jQuery.sub() function

Tags:

jquery

Can someone explain me the new sub function of jQuery http://api.jquery.com/jQuery.sub/

Please give your own example that's easy to follow.

like image 376
learningdb Avatar asked Feb 01 '11 11:02

learningdb


1 Answers

Side-by-side jQueries

It creates a side-by-side jQuery object with different capabilities. You could provide some plugins in one and others in the other jQuery instance created by jQuery.sub().

Real-world example

One usage example I can think of is having two public plugins with the same name but different functionality/working so you could load the first in one jQuery and the second in the other jQuery. This way you'd be able to use both even though they share the same name.

But otherwise I think function's quite nicely explained on jQuery documentation anyway. I don't think it needs any additional explanation. It only lacks some credible example that shows a very useful usage scenario.

Actual example

jQuery plugins these days will have to be changed to support this functionality, because they usually do this:

(functio($){
    // plugin code
})(jQuery);

As you can see this function closure parameter is hardcoded to jQuery. To include a particular plugin in its own jQuery realm (that you as a developer define), this code should be changed to:

var $$ = jQuery.sub();
(functio($){
    // plugin code
})($$);

But this would mean that developers would always have to change plugin code which is not really helpful. I suppose jQuery will have to come up with some sort of plugin manager so loading plugins would only load them inside this manager and you'd have to include them in jQuery object by using this manager and providing jQuery realm.

I don't see any other possibility of making plugins generic so they can be used in any jQuery instance without changing plugin code.

Example presented in original documentation is some sort of a let them see how it can be done but I don't think that's a very good example bacuse it just puts all sub() plugins under a common original jQuery plugin (in that example it's myplugin()).

like image 168
Robert Koritnik Avatar answered Sep 20 '22 19:09

Robert Koritnik