Reputation: 6836
I found this great resource on patterns for splitting and subbing your Backbone views
http://ricostacruz.com/backbone-patterns/#sub_views
However, there doesn't seem to be any existing patterns for how one should approach the model-add/view-create pattern in a way that accommodates a single model easily over multiple view cases.
Let's say, for instance, I have a User model, but I have two contexts for the Users on the page. For the purposes of illustration, let's say they're a Poster and a Commenter. The Poster's view (render and actions) are different from the Commenter's view.
Backbone says the best way to create new views is through the instantiation of a model, so outside of doing some sort of arbitrary property setting on the model (e.g. { poster : true } or { commenter : true }) and using that property and a case/switch to direct the model to instantiate the "right" view, what's a more agnostic and "Backboney" way of handling this problem?
Upvotes: 1
Views: 1418
Reputation: 5070
Here is a modified sample from here.
var PhotoRouter = Backbone.Router.extend({
routes: { "photos/:id": "route" },
route: function(id) {
var item = photoCollection.get(id);
var view = new PhotoView({ model: item });
var view2 = new PhotoView2({ model: item });
something.html( view.render().el );
somethingElse.html( view2.render().el );
}
}):
Now, Backbone doesn't really have a preferred way to structure your app. You could do this, creating and showing the views in the router. Or, sometimes it is good to create your own AppController object, so you can leave the router to just routing. Or, you could create a BaseView of some sort, which would create your sub-views...
But, the important thing is that both your views know nothing about each other. And both will display and respond to the changes in the model in their own way. Also, the model knows nothing about the views displaying it.
Another useful idea is the event aggregator. Using this, your different components can communicate without tightly coupling themselves.
There are some extensions for Backbone, like (Backbone Marionette), which add some more structure. You could look into those too.
Upvotes: 2