How do I get the basic Backbone route after receiving the document?

Level 7 codeschool.com As part of the basic course, the following code was given below and indicated that it could all be run with the following jquery

$(function(){ TodoApp.start() })

      

which is being called Backbone.history.start

. But how the call Backbone.history.start

ultimately results in what gets index

called so that gets fetch

called to populate the collection of models 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);
  }
}));

      

+3


source to share


1 answer


If you look at the Backbone source , you can see what's going on.

At the end, History.start

you will see what 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

. Because there is a handler that matches the "index" called by the callback.

+4


source







All Articles