I'm currently working on a large web app built on backbone.js and have been having a lot of issues with organization, "zombies," etc. so I've decided to do a major refactor of code. I've already written a bunch of helper functions for dealing with the "zombies"; however, I'd like to start from the very beginning and create a nice structure/organization to the code. I haven't found many great tutorials/examples on large-scale backbone.js organization so I've sort of started from scratch and would like to see if I can get some opinions on where I've begun.
I've obviously set up my code within a global namespace; but I'd also like to keep that namespace rather clean. My main app.js keeps the class files themselves separate from the global namespace; you can register a class (so that it can be instantiated) by using the reg() function and the inst() function instantiates a class from the classes array. Thus, besides the 3 methods, the MyApp namespace only has Router, Model and View:
var MyApp = (function () {
var classes = {
Routers: {},
Collections: {},
Models: {},
Views: {}
};
methods = {
init: function () {
MyApp.Router = MyApp.inst('Routers', 'App');
MyApp.Model = MyApp.inst('Models', 'App');
MyApp.View = MyApp.inst('Views', 'App');
Backbone.history.start();
},
reg: function (type, name, C) {
classes[type][name] = C;
},
inst: function (type, C, attrs) {
return new classes[type][C](attrs || {});
}
};
return methods;
}());
$(MyApp.init);
Within the Models, Collections, Routers and Views, I work as usual but then need to register that class at the end of the file so that it could be instantiated at a later point (without cluttering the namespace) with:
MyApp.reg('Models', 'App', Model);
Does this seem like an unnecessary way to organize code? Do others have better examples of how to organize really large projects with many Routers, Collections, Models and Views?