Search code examples
javascriptbackbone.jsrequirejsamd

Using requirejs means no more global variables?


Does using requirejs means I will not be dealing with global variables anymore?

I am starting to implement requirejs in my project. Before using requirejs, I was attaching my custom Backbone Router class to a namespace variable:

app.Router = Backbone.Router.extend({customStuffInHere});

Say that I am now defining it as a "module":

define(['backbone'], function(Backbone) {
    return Backbone.Router.extend({customStuffInHere});
});

There is no problem with that, as my custom router is in it's own file Router.js. So it follows the convention one module per file.

When I was creating an instance of this router before requirejs, I was just doing:

....code....
app.router = new app.Router();
....code....

Now I would have to create an entire new file just for this instantiation and include it in the current module?

Am I doing things right?

Edit: I guess my question is how can I have a single router model for all my application?


Solution

  • Use the relative path to your JS file without the .js extension. (Or use a relative path to baseUrl)

    By nature RequireJS modules are singletons, meaning you will get a reference to the same object in any define or require call

    require('./path/to/Router', function () {
      var router = new Router();
    }};