Jonathan Vanasco
Jonathan Vanasco

Reputation: 15680

What are good/best ways to handle jquery namespace collisions?

I'm using two jquery plugins. Both extend jquery with a prototype function removeTag. This causes the second-loaded plugin to work correctly, while the first one does not.

As a quick patch, I renamed the removeTag - and all calls to it - on the second plugin to something else.

Obviously, thats not a good solution. Upgrades will need to be manually edited, and there could be other namespace collisions that I haven't realized yet.

Can anyone recommend some effective strategies for dealing with this?

The two plugins I am using are:

Upvotes: 3

Views: 352

Answers (3)

DanRedux
DanRedux

Reputation: 9349

After loading in the first plugin, define the function with a different name $.fn.removeTagsPlugin=$.fn.removeTags then when you load in the second plugin it can happily overwrite $.fn.removeTags. This has limitations.. If the first plugin uses, internally, removeTags and it won't work if it uses the new plugin's version of removeTags, then this solution won't work.

Upvotes: 0

Eduardo Crimi
Eduardo Crimi

Reputation: 1601

You can add a js file with the code from below:

if (jQuery) {
    jQuery.namespace = function(namespace) {
            var names = namespace.split(".");
            var parent = window;
            for (var index = 0; index < names.length; index++) {
                    if (!parent[names[index]]) {
                            parent[names[index]] = function() {
                                    throw "Namespace, Cannot instantiate";
                            }
                    }
                    parent = parent[names[index]];
            }
    }

}

And on your scripts you can use it like the following:

$.namespace("Somejs.MyCustomjs");

And later on the Code refer to the full Namespace like:

SomeJs.MyCustomjs.myFunc();

hope It helps

Edit: I forgot to mention that on the declaration of your js class you netted to use the full namespace

Upvotes: 4

James Montagne
James Montagne

Reputation: 78650

One possibility would be to use jQuery.sub().

http://api.jquery.com/jQuery.sub/

This would allow you to create a copy of the jQuery object and have the one plugin use the copy.

// load jQuery
// load plugin1

var $origJQ = jQuery;
jQuery = jQuery.sub();

// load plugin2

jQuery.plugin2Stuff();
$origJQ.plugin1Stuff();

The big drawback though is that you would need to be sure to use the appropriate alias for jQuery when dealing with either plugin. If at least one of the plugins is just something you call once on load of your page though this may not be a problem.

EDIT: Apparently this is deprecated in 1.7 and will be moved to a plugin in 1.8

Upvotes: 0

Related Questions