Backbone.js Router initialization doesn't run immediately

后端 未结 3 616
名媛妹妹
名媛妹妹 2021-01-20 23:49

My code is as follows:

var AppRouter = Backbone.Router.extend({

    _data: null,
    _length: 0,
    _index: null,
    _todos: null,
    _subtodolist: null,
            


        
3条回答
  •  轮回少年
    2021-01-21 00:19

    Indeed the problem here is with initialize returning before the ajax call inside it has been resolved.

    What you can do is do something like the following in your entry point (typically $.ready())

    var self = this,
        p = $.ajax({
        url: 'data/todolist.json',
        dataType: 'json'
    });
    
    p.done(function (data) {
        AppRouter = new Backbone.Router({data: data});
        Backbone.history.start({ pushState: true });    
    });
    

    This will fetch the routes, and then initialize the router with them as well as start Backbone.history. Obviously you don't need to do the ajax call again in initialize, just use the data passed in options.

提交回复
热议问题