如果app.js没有准备就绪,如何使用this.template?

时间:2012-05-30 20:22:12

标签: templates backbone.js underscore.js

我尝试关注http://ricostacruz.com/backbone-patterns/#inline_templates以避免http://ricostacruz.com/backbone-patterns/#abuse,但我有一个典型的观点:

// in app.js
App.MyView = Backbone.View.extend({
    className: "ui-widget-content",
    template: _.template($("#myTemplate").html()),
    render: function() 
    {
        this.$el.html(this.template(this.model.toJSON()));
    }

然后我就像这样包含app.js

<script src="./js/jquery-1.7.2.min.js"></script>
<script src="./js/jquery-ui-1.8.20.custom.min.js"></script>
<script src="./js/underscore.js"></script>
<script src="./js/backbone.js"></script>
<script src="./js/app.js"></script>

浏览器抱怨App.MyView.template中的$("#myTemplate")行是null(因为文档还没有准备好?)。我该怎么办?

3 个答案:

答案 0 :(得分:2)

为什么不延迟加载模板?首次使用时编译模板,并在视图的“类”中缓存已编译的模板。您甚至可以使用以下内容添加基本视图来处理此缓存:

var BV = Backbone.View.extend({
    template: function(data) {
        if(!this.constructor.prototype._template)
            this.constructor.prototype._template = _.template($('#' + this.tmpl_id).html());
        return this._template(data);
    }
});

然后你可以有这样的事情:

var V = BV.extend({
    tmpl_id: 'tmpl',
    render: function() {
        this.$el.html(this.template(this.model.toJSON()));
        return this;
    }
});

并且#tmpl模板将在第一次使用时进行编译,并且最多只编译一次。

演示:http://jsfiddle.net/ambiguous/hrnqC/

注意演示中的 no wrap(head)并查看控制台以查看正在编译的内容和频率。

答案 1 :(得分:1)

我对此的快速解决方法是在视图初始化时编译模板..

App.MyView = Backbone.View.extend({
    className: "ui-widget-content",
    template: '#myTemplate',
    initialize: function(){
        this.template = _.template($(this.template).html());
    },
    render: function(){
        this.$el.html(this.template(this.model.toJSON()));
    }

然后其他所有内容仍然相同,您可以将渲染方法放在基类中。

答案 2 :(得分:0)

最简单的做法就是不缓存模板:

App.MyView = Backbone.View.extend({
    className: "ui-widget-content",
    render: function() 
    {
        var template = _.template($("#myTemplate").html())
        this.$el.html(template(this.model.toJSON()));
    }