渲染与骨干的把手模板

时间:2012-09-15 17:15:36

标签: backbone.js handlebars.js

我有一个Backbone视图(见下文),我认为这是正确的做法

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没有像在控制台中那样呈现。有什么想法吗?

1 个答案:

答案 0 :(得分:3)

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

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

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

你应该做两件事:

  1. 如果activities为空,请修复模板以执行合理的操作(例如,显示某种 loading ... 消息)。
  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;
    }
    
  3. 我也切换到this.$el,当Backbone已经为您提供$(this.el)时,无需this.$el

相关问题