Backbone.js 路由器初始化不会立即运行 [英] Backbone.js Router initialization doesn't run immediately

查看:13
本文介绍了Backbone.js 路由器初始化不会立即运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码如下:

var AppRouter = Backbone.Router.extend({

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

    routes: {
        "*action": "index",
        "category/:name": "hashcategory"  
    },

    initialize: function(options){
        var self = this;
        if (this._index === null){
            $.ajax({
                url: 'data/todolist.json',
                dataType: 'json',
                data: {},
                success: function(data) {
                    self._data = data;
                    self._todos = new TodosCollection(data);
                    self._index = new CategoriesView({collection: self._todos});
                    //self._index.render(); 
                }
            });
            return this;
        }
        return this;
    },

    index: function(){
        this._index.render();
    },
 ....

但是当我开始时,firebug 控制台面板总是告诉我 this._indexindex 函数中为空.我必须在 $.ajax success 回调函数底部使用 self._index.render() 来使主页呈现(上面​​已注释掉).似乎 index 函数在 initialize 函数之前运行.怎么会发生这种情况,我该如何解决?

But when I get started, firebug console panel always tells me this._index is null in the index function. I have to use self._index.render() at the bottom of the $.ajax success callback function to make the homepage render(which is commented out above). It seems that index function runs before the initialize function. How could that happen and how can I fix it?

顺便说一下,在routes中,如果我使用"": "index",它是行不通的.我必须使用 "*action": "index".但是我在其他地方了解到默认 url 可能只是空字符串.为什么我这里不能用?

By the way, in the routes, if I use "": "index", it will not work. I have to use "*action": "index". But I have learned somewhere else that the default url could be just empty string. Why can't I use it here?

推荐答案

确实,这里的问题是 initialize 在内部的 ajax 调用得到解决之前返回.

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

您可以做的是在您的入口点执行以下操作(通常为 $.ready())

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 });    
});

这将获取路由,然后然后用它们初始化路由器并启动Backbone.history.显然不需要在初始化的时候再次调用ajax,直接使用options传入的数据即可.

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.

这篇关于Backbone.js 路由器初始化不会立即运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆