2013-02-15 124 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'的處理函數,所以調用回調函數。