Search code examples
backbone.js

Passing data from main application view to some subviews


Please consider following Backbone application structure:

AppView
    Subview
        FirstSubviewInQuestion
    Subview
        Subview
            SecondSubviewInQuestion

Application view creates and stores a collection of special items. At a certain time the first and the second subview needs to get access to that collection. Now what is the best way to pass the collection it to them?

I myself see some ways, yet each has a downside:

1) Create instance of that collection not inside the App View but even more globally and then pass it around as dependency (project uses RequireJS; so it would be passed to AppView and both Subviews). Downsides: app view is supposed to be the top most element in application. Yet suddenly we have some instances of collections floating above.

2) Or I can do following:

// some subview
var collection = {};
Backbone.trigger( "item:getSpecialItems", collection);
// now the collection has data

// app view
this.listenTo( "item:getSpecialItems", function(obj) {
    // copy collection to passed object
    _.extend(obj, this.specialCollection);
});

Downsides: we are triggering a global event. We know that only the app view would respond, but it feels like a bad design. Plus, this way to pass the collection seems like a hack.

Maybe there are some other clever ways to do it?


Solution

  • I would say #1.

    app view is supposed to be the top most element in application

    Right, but you're talking about (I think) a Collection, not a View; the two are totally separate parts of your application (in MVC the first is the "M" and the second is the "V"). By definition, if your views are driven by your data, the data must be "higher" (in the dependency tree) than any view, so I don't see anything wrong with that approach.