How does Backbone initial route get called after document ready?
backbone.js, jquery
Solution
If you look at the Backbone source, you can see what is happening.
At the end of `History.start`, you can see that it calls `loadUrl`, which looks like this:
// Attempt to load the current URL fragment. If a route succeeds with a
// match, returns `true`. If no defined routes matches the fragment,
// returns `false`.
loadUrl: function(fragmentOverride) {
var fragment = this.fragment = this.getFragment(fragmentOverride);
var matched = _.any(this.handlers, function(handler) {
if (handler.route.test(fragment)) {
handler.callback(fragment);
return true;
}
});
return matched;
},
When you add routes, they are added to `this.handlers`. Since there is a handler that matches 'index' that callback is called.
Problem
Level 7 of codeschool.com Backbone course had the following code below and stated that the entire thing could be kicked off with the following jquery ``` $(function(){ TodoApp.start() }) ``` which will call `Backbone.history.start`. But how does the call to `Backbone.history.start` eventually lead to `index` being called so that `fetch` is called to populate the model collection `todoList`. ``` var TodoApp = new (Backbone.Router.extend({ routes: { "": "index", "todos/:id": "show" }, initialize: function() { this.todoList = new TodoList(); this.todosView = new TodoListView({collection: this.todoList}); $('#app').append(this.todosView.el); }, start: function(){ Backbone.history.start({pushState: true}); }, index: function(){ this.todoList.fetch(); }, show: function(id){ this.todoList.focusOnTodoItem(id); } })); ```