Search code examples
backbone.js

Backbone best practices where to fetch models/collections


I've inherited a codebase that follows the format of: a router sets a controller, the controller fetches the collection/model needed, then the controller set/passes the view the collection/model.

The current View I'm working on loads a collection, and now I need to build in a feature where I fetch a single model after the view has rendered, based on an id clicked (note the model is from a different collection).

I only want to load the model when/if they click a button. So my question is, can I setup the model/fetch in the View, or should I be doing that in the controller? Is there a backbone best practice when adopting a controller/view setup like this?

I primarily ask because it seems easier for me to add this new feature right in the View. But is that a bad practice? I thought so, so I started down the path of triggering an event in the View for the controller to the fetch the model, and then somehow pass that back to the View (but I'm not sure really how to even do that)...it seems like a lot of unnecessary hoop jumping?


Solution

  • Its OK to fetch collection via views. As 'plain' backbone does not Controller, View in charge of it responsibilities.

    But imho fetch collections via controller is better practice, its easier to scale and support and test.

    The only difficulty is to set communication between Controller and View context event. One of the approach is trigger Message Bus event on context event like

    events: {
       'click .some': function() {
           this.trigger('someHappend', { some: data })
       }
    }
    

    and listen to this event in Controller

    this.on(someViewInstance, 'someHappend', function() {
        // do something in controller
    })
    

    If you already inherited code with structure you described you'd better follow it. Also you might be interested in MarionetteJS as significant improvement. Also highly recommend you to checkout BackboneRails, screencasts not free but very usefull, especially in large scale app maintain