0

我刚刚开始将backbone.js 用于我正在从事的项目。

我目前已经按照我想要的方式设置了模型、集合和视图。我正在从服务器上的 REST 应用程序获取数据。

客户可以登录应用程序;目前我正在将该信息输入 underscore.js 模板,但我希望模板是动态的。根据客户的不同,一些选项会有所不同。

我的感觉是,让模板进行特定的 ajax 调用以获取动态信息会完全违背使用backbone.js 的目的。是否可以让主干和下划线从 xhr 请求中加载模板?还是有更好的方法来做到这一点?

我在这里先向您的帮助表示感谢。

4

1 回答 1

2

就下划线而言,模板只是一个字符串,因此您可以从任何您想要的地方获取该字符串。所以你可以这样做:

render: function() {
    var that = this;
    $.get('/some_template', function(tmpl) {
        that.$el.html(_.template(tmpl, that.model.toJSON()));
    });
    return this;
}

在现实生活中,您可能希望将其隐藏在一个仅从服务器获取特定模板一次的简单缓存对象后面。

或者,您可以让您的服务器代码找出需要哪组模板并将它们嵌入到<script>元素中:

<script id="tmpl1" type="text/template">
    Some template code...
</script>
<script id="tmpl2" type="text/template">
    Some template code...
</script>
...

并将模板从<script>s 中拉出:

render: function() {
    var tmpl = _.template($('#tmpl1').html());
    this.$el.html(tmpl(this.model.toJSON()));
    return this;
}

再一次,您可能希望在tmpl某处缓存已编译的模板,或者甚至在定义视图类时对其进行编译(当然,假设 DOM 已经准备就绪):

var V = Backbone.View.extend({
    template: _.template($('#tmpl1').html()),
    //...
    render: function() {
        this.$el.html(this.template(this.model.toJSON()));
        return this;
    }
});
于 2012-05-10T22:23:12.397 回答