2
votes

I'm creating a web application using Backbone.js and Handlebars.js (with Underscore.js and jQuery as dependencies for Backbone). I'm loading modules for the app with requirejs.

Following the instructions here:

http://requirejs.org/docs/jquery.html#noconflictmap

and here:

http://requirejs.org/docs/api.html#config

So my requirejs config looks like:

  map: {
    '*' : { 'jquery': 'jquery-private' },
    'jquery-private': { 'jquery': 'jquery' }
  },
  shim: {
    'underscore' : {
      exports: '_',
      init: function() { return this._.noConflict(); }
    },
    'backbone'   : {
      deps: ['underscore', 'jquery'],
      exports: 'Backbone',
      init: function(_, $) {
        // need to manually set Backbone.$ since it looks for it on the global object
        this.Backbone.$ = $;
        return this.Backbone.noConflict();
      }
    },
    'handlebars' : { exports: 'Handlebars' }
  }

I'm loading local copies of my dependencies by calling noConflict() on backbone, underscore, and jquery. However, Handlebars does not have a noConflict method; if I attempt to configure the shim for it in the same way as backbone & underscore, I get an error:

Uncaught TypeError: Object #<c> has no method 'noConflict'

No real surprise there, but then I'm concerned about conflicts! Is there a workaround? Can I somehow manually achieve the same goal by writing my own version of the noConflict for Handlebars? What would that look like?

1

1 Answers

0
votes

As I understand, purpose of noConflict is to release some namespace (or, in other words, global variable). I think, you could accomplish it in following way:

  1. Add to Handlebars some fake dependency (it may be simple AMD module, written by yourself)
  2. in Handlebars shim config, use init option in following way:

handlebars   : {
   deps: ['myFakeModule'],
   init: function(myFakeModule) {
      myFakeModule.Handlebars = this.Handlebars;
      this.Handlebars = undefined;
      return myFakeModule.Handlebars;
   }
}

This is a theory and a bit hacky, but it might do the trick.