在获取之前渲染骨干

时间:2012-09-28 12:37:54

标签: javascript backbone.js

我正在使用主干LayoutManager来管理我的视图。

我在调用render之前获取模型数据时出现问题,这显然会因为Ajax成功回调尚未完成而引发错误。

解决此问题的一种方法是在路由器中获取模型并将app.useLayout("main").render();放入success方法中。这是正确的方法还是有更好的解决方案?

路由器代码:

app.useLayout("main").setViews({
    ".place-detail": new Place.Views.Show({
      model: new Place.Model({ place_id: place_id })
    })
}); 

app.useLayout("main").render();

查看代码:

Views.Show = Backbone.View.extend({
    initialize: function(options) {
        _.bindAll(this,"render");
        this.model.on("change", this.render, this);
        this.model.fetch();
    });
});

1 个答案:

答案 0 :(得分:2)

Backbone的fetch接受成功和错误回调,因此如果你想在执行更多代码之前等待提取完成,请将其置于成功回调中:

Views.Show = Backbone.View.extend({
    initialize: function(options) {
        var _this = this;
        _.bindAll(this,"render");
        this.model.fetch({
          success: function(model, response) {
              _this.render();
              _this.model.on("change", _this.render, _this);
              _this.someOutsideFunctionCall();
          },
          error: function(model, response) {
              console.log("Error Fetching.");
          }
        });
    };
});

我在CoffeeScript中编写了很多代码,所以我不确定我是否得到了所有({}); s是正确的,但这是它的基本要点。注意_this = this的声明,因为如果你试图在回调函数中引用它,它就不会知道你在说什么。