Search code examples
javascriptbackbone.jsthorax.js

Where to instansiate my collections in a Backbone/Thorax application?


I'm wondering where is the best place to instantiate my Collections in a Thorax (or Backbone) application. I couldn't find a decent answer to that, but I basically found 3 approaches, most are from Backbone, as there is not enough discussions on Thorax:

  • Create them in the collection file itself and add to application namespace. (For example: do app.Todos = new Todos() in the end of the collections/todos.js file). I don't like this approach because it will always create all the collections, even if I don't need them
  • Create them in the module's router (in Thorax with Lumbar, each thorax module has its own router). Then create the view and pass them to the view. This way it will guarantee I will only create the collections needed by routes
  • Create them in the view. I haven't really found a good example for that, but in Backbone Fundamentals it is mentioned that most of the controllers responsibility is handled by the views, but I don't love the idea of instantiating collections in views, but it will make things simpler as a view definitely knows which collections it needs.

Solution

  • I think the answer is largely dependent on the specifics of your application (this tends to be the way with Backbone-based projects). I typically have tried to pass collections to a view's constructor, to avoid having to call setCollection later. I'd definitely avoid creating them in the collection file itself. I tend to think of instantiation in general as a "need to know" decision: the Collection class itself doesn't need to know how/when it will be used, whereas sometimes the router does (if there are specific arguments), and the view always does, though sometimes it's not possible to manage object creation within the view alone.

    If you're looking for a decent-sized example of a Thorax project, you can look at popHealth, which has a Rails back-end coupled with a Thorax front-end. The Thorax code is found in app/assets/javascripts, and is written in CoffeeScript.