Monday, November 21, 2011

Don't Set window.location in Backbone.js

‹prev | My Chain | next›

Up today: a quick follow up to the post from yesterday about injecting a default route for testing purposes.

My Recipes with Backbone co-author, Nick Gauthier, suggested that my routing leaves a little to be desired. Specifically, rather than manually manipulating window.location, I should be using Backbone.history.navigate().

I should know better by now, so I give it a try:
  var Routes = Backbone.Router.extend({
    // ...
    _setDefault: function() {
      console.log("[setDefault]");
      var month = Helpers.to_iso8601(new Date).substr(0,7);
      Backbone.history.navigate('#month/' + month);
    },
    // ...
  });
Hopefully that won't break too much. And by "break", I mean expose related bad assumptions on my part. Unfortunately, when I load that back up in my browser, I now get an empty calendar with no appointments:


Back when I was setting window.location, I could rely on my month route kicking in after I my new location matched the month route:
  var Routes = Backbone.Router.extend({
    routes: {
      // ...
      "month/:date": "setMonth"
    },
    // ...
    setMonth: function(date) {
      console.log("[setMonth] %s", date);
      this.application.setDate(date);
    }
  });
Now, it seems that I have to do it manually:
    _setDefault: function() {
      console.log("[setDefault]");
      var month = Helpers.to_iso8601(new Date).substr(0,7);
      Backbone.history.navigate('#month/' + month);
      this.setMonth(month);
    },
Thankfully, by re-using a parameterized route, not too much need change. And with that, I have my calendar populated correctly with appointments:


Best of all, my specs still pass:


Thanks, Nick! That feels much better. Up tomorrow: I will follow-up to see if I can remove any code as a result of this change.


Day #212

2 comments:

  1. Try passing true as the second parameter of navigate and removing the setMonth function, it will do wonders (or atleast it should).

    ReplyDelete
  2. Hahaha. I should read the documentation some time, eh? I was in a bit of a hurry on that post, so I got sloppy. Thanks for pointing out my mistake. That looks much better :)

    ReplyDelete