I'm creating a single page application with backbone.js and would like to know the best way to handle changing the title. I was thinking of having a 'title' option in the view and have the router (somehow) get set the document.title. Has anyone implemented anything similar? Thanks
why not use the evented nature of Backbone.js.
First off I don't think it's up to the Router to delegate the updating of the Document Title. Especially if you're working with larger client-side applications you want to keep it simple and make sure each part of your application fulfils a specific task.
The router is there to delegate routes, nothing more.
what I'd suggest instead is (depending on how you initialize your application) to create an application-level event aggregator.
var app = new Application();
app.eventAggregator = _.extend({}, Backbone.Events);
and bind an event to your app as such:
app.eventAggregator.on('domchange:title', this.onDomChangeTitle, this);
where in your Application construct
onDomChangeTitle: function (title)
{
$(document).attr('title', title);
}
and now, instead of having to leave it up to the Router to always grab the title and making sure there's getTitle
method in each view, you can - inside your view and therefore, ANY view - trigger the following event when you render or initialize the view:
app.eventAggregator.trigger('domchange:title', this.title);
it makes for cleaner and leaner code in my opinion, but then again, that's just an opinion.