Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Backbone initial route get called after document ready?

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);
  }
}));
like image 799
user782220 Avatar asked Feb 16 '26 08:02

user782220


1 Answers

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.

like image 176
Paul Hoenecke Avatar answered Feb 18 '26 21:02

Paul Hoenecke



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!