【问题标题】:Underscore.js template with Backbone.js error带有 Backbone.js 错误的 Underscore.js 模板
【发布时间】:2012-06-22 00:37:04
【问题描述】:

下面的行完全失败了。

template: _.template($('#test').html()),

尝试按照https://github.com/ccoenraets/backbone-jquerymobile 中的一个简单示例将jQuery mobile 与Backbone.js 一起使用。我在网络检查器中遇到的错误是:TypeError: 'null' is not an object (evalating 'str.replace') 位于 underscore.js 的第 913 行。以这种方式使用 is _.template:

template: _.template("<h1>To Do</h1>"),

可行,但为了合并 jQuery 移动样式,这种方式行不通。

tod​​o.js

TodoBb.Views.ComCentersTodo = Backbone.View.extend({

template: _.template($('#test').html()),


render: function() {
    $(this.el).html(this.template());
    return this;
}
});

main.html

<script type = 'text/template' id = 'test'> <h1>To Do</h1> </script>

【问题讨论】:

  • 那么问题出在哪里? jQuery 移动样式没有出现吗?为此,您需要触发像$("...").trigger("create") 这样的创建事件,虽然现在只是查看文档,但我找不到创建事件

标签: jquery-mobile backbone.js underscore.js


【解决方案1】:

当你的视图被解析时,DOM 还没有准备好:

TodoBb.Views.ComCentersTodo = Backbone.View.extend({
    template: _.template($('#test').html()),
    //...
});

所以$('#test').html()null 而你实际上正在这样做:

TodoBb.Views.ComCentersTodo = Backbone.View.extend({
    template: _.template(null),
    //...
});

_.template 的内部使用replace,同时将模板转换为 JavaScript 函数。

你有几个选择:

  1. TodoBd.Views.ComCentersTodo 定义放在$(document).ready() 处理程序中:

    $(function() {
        TodoBb.Views.ComCentersTodo = Backbone.View.extend({
            template: _.template($('#test').html()),
            //...
        });
    });
    
  2. 在需要之前不要编译模板:

    TodoBb.Views.ComCentersTodo = Backbone.View.extend({
        //... no template in here
        render: function() {
            var html = _.template($('#test').html(), this.model.toJSON());
            this.$el.html(html);
            return this;
        },
        //...
    });
    

作为 2 的变体,您可以在某处缓存已编译的模板函数,并且仅在第一次使用时调用 _.template($('#test').html())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-04
    • 2011-11-16
    • 1970-01-01
    • 2012-07-12
    • 2012-02-14
    相关资源
    最近更新 更多