Backbone is great but it still needs some polishing. These organizational tips should help get you up and running.
When I first started out with Backbone, the recommended directory structure rubbed me the wrong way:
- Why are collections glorified and given their own directory? They’re still “models”, no?
- Why are templates glorified and given their own directory? Are they model-code? No. Are they controller/router code? No! A template’s sole existence is confined to views.
To use that structure in the asset pipeline, you’ll need to set up your requires like so:
#= require_tree ./models
#= require_tree ./views/templates
#= require_tree ./views
#= require_tree ./routers
Collections are models (just not Models)
Right now you might be thinking, “wait… where the hell did the collections go?” Well for now I’m lumping the model and collection definitions into a single file named after the model. For example, if I have a Surfboard model, /models/surfboard.js.coffee would look something like this:
Until either class expands significantly, this’ll do me just fine.
Notice that I also create a global instance of the collection, named after the model (capitalized and pluralized). This collection instance will be bootstrapped by the rails view and will always be available for event bindings by any class.
Bootstrap your collections
If you know you’re going to need the data, bootstrap it. It’ll speed up the initial user interactions and saves you a round trip to the server.
Only namespace when you need to
new MyApp.Backbone.Models.MyModel( yadayada ). It makes programming unenjoyable and leaves a bad taste in my mouth. If the class is a class you’ll be using a lot and is global in nature, just define it in the global context (within the rails 3.1 asset pipeline this implies prepending
window. to your class names).
THIS ONLY APPLIES TO APPLICATION CLASSES! Libraries should always be namespaced.
Namespacing classes this way is an art and not a science, just try to be consistent. Here’s an example of my naming scheme: let’s say I’m building a site that sells bikinis. I’ll be dealing with bikinis all over the place and Backbone.Models.Bikini just isn’t sexy enough for me. Instead, my model class will be Bikini, the collection will be BikiniCollection, and the primary view will be — drum roll please — BikiniView. All in the global namespace — easy to write, easy to read, easy to comprehend. We’re done here.
That’s it for now. More to come later. Hopefully this saves you from some of the initial organizational-headaches I suffered while readying Kumu for Backbone.