【问题标题】:Rendering Handlebars template with Backbone使用 Backbone 渲染 Handlebars 模板
【发布时间】:2012-09-08 12:01:50
【问题描述】:

我有一个我认为做正确的事情的主干视图(见下文)

Index = Backbone.View.extend({
render: function() {
        var activities = new Activities();
        activities.fetch();
        var tpl = Handlebars.compile($("#activities-template").html());
        $(this.el).html(tpl({activities: activities.toJSON()}));
        return this;
      }
});

如果使用 Chrome JS 控制台执行 render() 函数中的每一行,我会得到预期的结果,我传入的元素会填充模板输出。但是,当我使用以下命令运行它时

var i = new Index({el: $("body")})
i.render()

"i.$el" 完全是空的——HTML 没有像在控制台中那样被渲染。任何想法为什么?

【问题讨论】:

    标签: backbone.js handlebars.js


    【解决方案1】:

    fetch 是一个 AJAX 调用,因此无法保证 activities.toJSON() 在您执行此操作时会为您提供任何数据:

    activities.fetch();
    var tpl = Handlebars.compile($("#activities-template").html());
    $(this.el).html(tpl({activities: activities.toJSON()}));
    

    在您尝试使用 activities 之前,在控制台中执行代码可能会给 AJAX 调用时间以返回一些内容。

    你应该做两件事:

    1. 如果activities 为空,请修复您的模板以执行一些明智的操作(例如显示正在加载... 消息)。
    2. 将视图的render 附加到集合的"reset" 事件:

      initialize: function() {
          // Or, more commonly, create the collection outside the view
          // and say `new View({ collection: ... })`
          this.collection = new Activities();
          this.collection.on('reset', this.render, this);
          this.collection.fetch();
      },
      render: function() {
          var tpl = Handlebars.compile($("#activities-template").html());
          this.$el.html(tpl({activities: this.collection.toJSON()}));
          return this;
      }
      

    我也切换到this.$el,当Backbone已经给你this.$el时,不需要$(this.el)。

    【讨论】:

    • 感谢您的回答!当我实现这一点时,我必须改变一件事:我相信activities.toJSON() 应该是this.collection.toJSON()。无论如何,当我进行更改时,我会得到Cannot call method 'toJSON' of undefined,因为在调用render 时this.collection 仍然未定义。如果我取出 reset 回调处理程序它可以工作。所以我四处挖掘并想出了这个(对不起,jsfiddle):example
    • @schleg:this.collection.toJSON() 是对的,这就是我没有测试我的代码的结果。 “未定义”错误可能是因为 render 未使用 _.bindAll 绑定,您也可以在我的更新中说 this.collection.on('reset', this.render, this);(注意第三个参数)。
    • 啊,所以_.bindAll 一直是关键。谢谢 - 现在看起来有点愚蠢的问题,但你是帮助的冠军:)
    • 谢谢,这很好。我还尝试了 model.attributes,它也可以正常工作,但我猜 toJSON 将是使用 Backbone.Model 的更标准方式?
    • @JoshGough: model.toJSON() 是常用的方法(默认情况下只使用_.clone(model.attributes))。
    猜你喜欢
    • 2015-07-23
    • 2013-01-22
    • 2013-01-27
    • 1970-01-01
    • 2014-03-11
    • 1970-01-01
    • 2011-11-02
    • 2014-06-05
    • 1970-01-01
    相关资源
    最近更新 更多