I am working on a big Backbone.js application. The code is modular structured using require.js.
Now I see a lot of backbone code and tutorials doing this:
window.app = ( window.app || {} );
after they will assign model definitions and Collection instances to that global object, like so:
Task = Backbone.Model.extend({ /*...*/ });
Tasks = Backbone.Collection.extend({ /*...*/ });
window.app.Task = Task;
window.app.Tasks = new Tasks();
// do this with all your models and collections
I like this approach for its simplicity and for not having to deal with where and when to instantiate a collection. But it somehow seems wrong to first separate the code into tiny bits using require.js and after assign all together to a global variable (apart from that global variables are generally bad codestyle in javascript).
So what is your take on this, what are the pros and cons of this approach and how do you deal with your objects in Backbone?
First of all its not that big a problem to pollute your global name space as you can wrap all your model in your own namespace:
When it comes to requirejs it depends on the size of your project. I think for smaller projects you can go without. The benefit of using requirejs isn’t the preventing of namespace pollution, its the better maintainability because you always see the dependencies of a module. You can write better unit tests, because you can test a module and mock out all its dependencies. So we rebuild a large Backbone app from a structure like the above example into something like this:
models/Task.js
collections/Tasks.js
app.js