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

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

问题描述

我的code是如下:

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();
    },
 ....

但是,当我上手,萤火控制台面​​板总是告诉我 this._index 指数空功能。我必须使用 self._index.render() $。阿贾克斯成功回调函数的底部,使网页渲染(这是上面的注释)。看来,首页功能初始化函数之前运行。怎么可能发生,我怎么能解决这个问题?

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?

顺便说一句,在路线,如果我用:指数,也不会工作。我必须使用*动作:指数。但我已经学会了别的地方,默认的网址可能只是空字符串。为什么我不能在这里使用它?

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?

推荐答案

事实上这里的问题是与初始化 Ajax调用返回之前,它里面已经解决。

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

这将获取的路由,而然后的初始化与他们的路由器以及启动 Backbone.history 。很明显,你不需要在初始化再做Ajax调用,只需使用选项中传递的数据。

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天全站免登陆