0

I'm wondering how people handle the following case in Backbone: usually when a user navigates to the root of your app, a certain set of data is loaded from the backend, processed right away and then displayed in the DOM.

There are links in the app that will navigate you to different sub-sections of it. The router catches the navigation and replaces the current page with whatever page you navigated to, all based on the same data that's already been fetched.

The problem is that the user could bookmark that internal/secondary URL and navigate to it "cold", as in before the data has had a chance to be fetched, without going through the root URL. Is there an idiomatic/conventional way of handling that situation (in the router, I'm assuming)?

One way is, in the various router path-handling functions, to always call a method that will check if there's sufficient data to complete the operation, and if not, fetch it and then proceed?

Alexandr Kurilin
  • 7,685
  • 6
  • 48
  • 76

1 Answers1

1

Backbone won't hit the initial route in your router before you call Backbone.history.start, so you can delay it until you've done the necessary setup. I typically define a start method on my application's main router. Looks something like:

var AppRouter = Backbone.Router.extend({
  start: function() {
    //init code here
    something.fetch({success: function() {
      //only call history start after the necessary initial setup is done
      Backbone.history.start();
    }});
  }
});

And then start the application using that method:

window.app = new AppRouter();
window.app.start();

It's good to remember that there is nothing confining you to build your application using only the predefined pieces provided by Backbone. If your startup code is heavy, it may not belong to the router. In such case you should define a helper function to encapsulate the startup logic, and leave the router out of it altogether:

//startup.js
function startup(onComplete) {
  //do initialization stuff...
  onComplete();
});

//main.js
startup(function() {
  Backbone.history.start();
});
jevakallio
  • 35,324
  • 3
  • 105
  • 112
  • So if I'm understanding you correctly (by cross-referencing the documentation), as long as you're not manually initializing the app anywhere (like calling "new AppView" at the end of the main $(function(){})), and instead rely 100% on the router to create the views based on the URL, you can do all the setup you want before calling Backbone.history.start(). Only then the route will be looked at. More or less correct? – Alexandr Kurilin Feb 20 '13 at 00:35
  • @AlexandrKurilin, exactly so. And if you need to setup some layout-type views etc, that's fine too. When you call `Backbone.history.start`, the current route will be matched. – jevakallio Feb 20 '13 at 00:53