Question

This might be quite simple, but I must say I'm a bit confused on this topic.

I'm writing code based on two popular libraries:

  • jQuery
  • underscore.js

I am just wondering what would be the best way to isolate the code and prevent conflicts and how to merge it with its dependencies?

By merging I mean putting them within the same file.

Was it helpful?

Solution

You could easily place the two of them in the same file, because the only things they turn global are window._, window.$ and window.jQuery. The other variables and functions are wrapped in a local scope, so there will be no conflict.


Edit: Your own code could be put in the same file too. And if you prefer to remove the globals, both jQuery and Underscore have a no-conflict method, which replaces the globals with their old values (often undefined). You could wrap your code in your own local scope and there'll be no problems anymore:

// jQuery and Underscore source here

// You code here, wrapped in a self-executing function:

(function($, _){

  // here you can add your code:
  $('#test').text('jQuery works');

  _(3).times(function(){
    alert('Underscore works' );
  });

})(jQuery.noConflict(true), _.noConflict());

// no jQuery nor Underscore here:

alert(typeof jQuery, typeof $, typeof _);

This looks quite tricky, but let me explain it very quickly. You can execute a function immediatly after defining it, like this:

(function(){
  alert('I am being executed');
})();  // <-- basically how you call a function normally: func();

And you can pass arguments in it:

(function(a){
  alert(a);
})('test');

Both $.noConflict() and _.noConflict() remove the global variables and return a reference to the jQuery and Underscore variable. So you can pass these in the self-executing function as arguments and everybody's happy (:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top