Backbone.js Router initialization doesn't run immediately

后端 未结 3 613
名媛妹妹
名媛妹妹 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-20 23:52

    It looks like this happens because this._index is only set within the ajax callback. Because this is asynchronous, there is no guarantee that it will have executed before the index event handler triggers.

    According to the docs, the models you need on initial load should be bootstrapped.

    If that's not possible, one way to structure this code might be to fetch your data when the route is hit, and bind a reset event to your view, e.g.

    var CategoriesView = Backbone.View.extend({
        initialize: function() {
            this.collection.on("reset", this.render);
    
        },
    
        ...
    
    var AppRouter = Backbone.Router.extend({
    
        _index: null,
        _todos: null,
    
        routes: {
            "": "index",
            "category/:name": "hashcategory"  
        },
    
        initialize: function(options){
            var self = this;
    
            self._todos = new TodosCollection();
            self._index = new CategoriesView({ collection: self._todos });
        },
    
        index: function(){
            this._todos.fetch();
        },
    

    You'd also need to setup your collection to construct an appropriate URL to request data/todolist.json.

提交回复
热议问题