Reputation: 3455
This is a quote from Derick Baileys blog ( creator of Backbone.Marionette):
But a router should never instantiate a view and manipulate the DOM directly with jQuery or placing the view in to the DOM
But I keep seeing code like this:
var Router = Backbone.Router.extend({
routes: {
"":home
},
home: function(){
// instance of a view object in a router
var homeView = new HomeView({model:model});
// do something with homeView
})
Can this be considered anti-pattern, although it is widely used ? From my perspective, it is a good idea to separate definiton from instantiation of objects (calling new HomeView() later). But does this is to be found in router ?
Upvotes: 2
Views: 289
Reputation: 2313
Someone else asked the same question in the comments of the article you are referring to. Here is the answer Derick gave to which I agree, I am copying it in order to keep things centralized.
These two examples are functionally the same:
Backbone.Router.extend({
routes: {
"foo": "showFoo"
},
showFoo: function(){
var fooView = new FooView();
fooView.render();
$("#someEl").html(fooView.el);
}
});
Backbone.Router.extend({
routes: {
"foo": "showFoo"
},
showFoo: function(){
FooApp.show();
}
});
FooApp = {
show: function(){
var fooView = new FooView();
fooView.render();
$("#someEl").html(fooView.el);
}
}
The difference between the two is coupling, cohesion, encapsulation, separation of concerns and the single responsibility principle. If I want to change how the FooApp shows the application's views and make things work, I shouldn't have to change the Router. These two concerns should be separated. I should have "one reason to change" for the router and for the FooApp (high level application object).
For a small demo app, #1 is ok. Anything more than 1 or 2 views, though, and the code becomes unmaintainable quickly. Having to sift through all of the cruft of doing the actual display so that you can see what the router is doing as a whole is a really bad idea in my experience.
For a larger example of this at play, check out my BBCloneMail sample project: http://github.com/derickbailey... - look at the BBCloneMail.Router.js file.
Upvotes: 4
Reputation: 1372
I prefer initialize all view only once in router.initialize() and then just render them in routing methods. But I don't think it make such a big difference.
Upvotes: 0