Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone and document.title

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

like image 490
Xerri Avatar asked May 07 '12 14:05

Xerri


People also ask

What is Backbone in programming?

Backbone. js is a model view controller (MVC) Web application framework that provides structure to JavaScript-heavy applications. This is done by supplying models with custom events and key-value binding, views using declarative event handling and collections with a rich application programming interface (API).

Is Backbone JS still relevant?

Backbone. Backbone has been around for a long time, but it's still under steady and regular development. It's a good choice if you want a flexible JavaScript framework with a simple model for representing data and getting it into views.

What is Backbone in HTML?

<script src="underscore-min.js" type="text/javascript" charset="utf-8"></script>

Is Backbone a MVC?

Backbone is a JavaScript MVC library and that's a key difference. In the JavaScript MVC context, a framework usually means that you need to configure your code to get things done. Maybe you need to add some code to your HTML page, or give a page element a certain ID class name.


2 Answers

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.

like image 112
Vincent Briglia Avatar answered Nov 02 '22 19:11

Vincent Briglia


Why are you all using jQuery to change the title of the document instead using pure Javascript? Faster, easier, cleaner...

document.title = 'new title';
like image 27
midudev Avatar answered Nov 02 '22 19:11

midudev