0

I'm working on an built out with backbone and backbone-layout-manager. When I need to do a view change, I need to update the page to a new title. I've tried adding a convenience method called setTitle,

setTitle: (new_title) ->
    document.title = new_title
    console.log "changed title to: #{new_title}"

that I can call in my router, on a route change. This works great, however, there's a problem. When I check my browser history, it's evident that it shows the title that was associated with the previous page. Example (1-3 in order of pages visited):

1. localhost/#/home/ - "Website"
2. localhost/#/blog/ - "Website - Home"
3. localhost/#/home/ - "Website - Blog"

I see that the router is not calling the route until after the url has changed and my browser, Chrome, has added the page to its history.

My question is, how can I update the title of the page so that the title is actively reflected in my browser history.

UPDATE: This is not a Safari issue, and IE kinda does its own thing.

film42
  • 1,095
  • 12
  • 22
  • Check if this other question helps you: http://stackoverflow.com/questions/9520638/backbone-js-history-on-route-change-event – Pablo Apr 10 '13 at 00:17
  • Thanks @Pablo, but AFAIK, that could only simultaneously changes the title as the route is firing, and I'm not sure if it'll help since the route is navigating the browser maybe before or after the route change, but I'll give it a shot. – film42 Apr 10 '13 at 00:35
  • UPDATE: As predicted, it did not update the title. I guess it's possible I can set each href="/#/.." to use navigate, but that seems really dirty to me. – film42 Apr 10 '13 at 00:43
  • UPDATE AGAIN: Even sites like Artsy.net have this problem. Maybe it just isn't solvable yet. – film42 Apr 10 '13 at 00:48
  • @film42 Sadly I don't think there is any solution. The hashchange event (which is used to detect your URL changes) will always be called after navigating to the new URL. Furthermore, your solution (use navigate for all the href, or even change the title onclick or whatever) won't fully work, because there's still the case the user changes the URL himself. Still, I'd be interested if you found a working solution :) – Loamhoof Apr 10 '13 at 07:58
  • Thanks, @Loamhoof I'll keep looking, but I think as of now the problem is up to the browser to determine when the title needs to be recorded to history. Hence Chrome being a problem and Safari working properly. – film42 Apr 10 '13 at 15:55

1 Answers1

2

I was able to achieve this simply by updating the document.title in each of my route callbacks.

Backbone.Router.extend({
  routes: {
    'posts': 'posts',
    'posts/new': 'newPost'
  },
  posts: function() {
    document.title = 'All Posts';
    // do something
  },
  newPost: function() {
    document.title = 'New Post';
    // do something
  }
})
Trav McKinney
  • 988
  • 8
  • 24