I am using the backbone-boilerplate, which you can find here.
I was wondering how to add global functionality, which isn’t explicitly tied to any specific collection, model, view, etc. An example would be a ‘logout’ function, which might look like this:
var logout = function(){
// Clear Favorites
// Handle asynchronous logging (all in-app logs are sent to the server at logout)
// Redirect to the login page
// Do other cleanup
}
Basically, this will handle numerous models/collections, including Favorites, Events, Logs, Users, and the application Router
If you look at the main.js file in the backbone-boilerplate, I have been adding these functions at the top (line 13) like this:
function(namespace, $, Backbone, Example){
// BEGIN MY APP LOGIC
namespace.app.logout = function(){
// Do logout here
};
// END MY APP LOGIC
var Router = Backbone.Router.extend({
This works fine, but the application logic can quickly grow out of control. My question is, what would be a better way to organize this code? If I had a Utils module and loaded that Utils module in, would it make more sense?
Cheers!
TLDR: http://addyosmani.github.com/backbone-fundamentals/ Advanced section.
Make it possible, then make it beautiful, then make it fast.
As you grow your app and make things work (possible), it will become apparent which functions belong together. Separate them into modules accordingly (beautiful).
I use require.js, but not backbone-boilerplate (bb has an AMD branch as well). The way I have organized my app is exactly as you describe, I have a utils module that has general purpose app stuff. I then add Auth, Notification, and Date formatting stuff to the utils module. I then include the utils module wherever I’m lazy and want all my util functions available.
Since they are all just modules/mixins, I can also include the auth/notification/date modules in any single module I need them in.