2013-02-15 65 views
3

codeschool.com主干课程水平7有以下代码下方,并指出,整个事情可以用下面的jQueryBackbone初始路由如何在文档准备好后调用?

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

它将调用Backbone.history.start拉开序幕。但是如何调用Backbone.history.start最终导致index被调用,因此调用fetch来填充模型集合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); 
    } 
})); 

回答

4

如果你看Backbone source,你可以看到发生了什么。

截至History.start末,你可以看到,它调用loadUrl,它看起来像这样:

// 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; 
}, 

当你添加路由,它们被添加到this.handlers。因为有一个匹配'index'的处理函数,所以调用回调函数。

相关问题