【问题标题】:Backbone render before fetch获取之前的主干渲染
【发布时间】:2012-09-29 03:38:54
【问题描述】:

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

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

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

路由器代码:

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

【问题讨论】:

    标签: javascript backbone.js


    【解决方案1】:

    Backbone 的 fetch 接受成功和错误回调,所以如果你想在执行更多代码之前等待 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 中编写了很多代码,所以我不确定我是否得到了所有 ({}); 的正确性,但这是它的基本要点。注意 _this = this 的声明,因为如果你尝试在回调函数中引用 this,它不会知道你在说什么。

    【讨论】:

    • 就个人而言,如果可能的话,我可能会将模型和集合的加载/获取保持在视图之外,以使它们更具可重用性和可测试性。
    猜你喜欢
    • 2013-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多