javascript - 未捕获的类型错误 : Cannot call method 'replace' of undefined backbone. js

标签 javascript html templates backbone.js underscore.js

我正在尝试使用 backbone.js 开发一个简单的 RSS 应用程序。我正在使用这个 backbone.js tutorial .定义模板时,第 2 行(模板)出现以下错误。 有人也可以告诉我为什么在教程中定义了 tagName: "li"吗?

uncaught TypeError: Cannot call method 'replace' of undefined backbone.js

Javascript

window.SourceListView = Backbone.View.extend({
    tagName:"li",
    template: _.template($('#tmpl_sourcelist').html()),

    initialize:function () {
        this.model.bind("change", this.render, this);
        this.model.bind("destroy", this.close, this);
    },

    render:function (eventName) {
        $(this.$el).html(this.template(this.model.toJSON()));
        return this;
    },

    close:function () {
        $(this.el).unbind();
        $(this.el).remove();
    }
});

HTML

 <script type="text/template" id="tmpl_sourcelist">
                        <div id="source">
                        <a href='#Source/<%=id%>'<%=name%></a>
                        </div>
                </script>

谢谢

最佳答案

你的错误就在这里:

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

_.template的一部分的内部涉及调用 String#replace 在生成已编译模板函数的过程中未编译的模板文本。该特定错误通常意味着您实际上是在说:

_.template(undefined)

如果没有 #tmpl_sourcelist 就会发生这种情况当你说 $('#tmpl_sourcelist').html() 时在 DOM 中.

有几个简单的解决方案:

  1. 调整您的 <script>订购以便您的 #tmpl_sourcelist在您尝试加载 View 之前出现。
  2. 在 View 的 initialize 中创建已编译的模板函数而不是在 View 的“类”定义中:

    window.SourceListView = Backbone.View.extend({
        tagName:"li",
        initialize:function () {
            this.template = _.template($('#tmpl_sourcelist').html());
            //...
    

至于tagName去,fine manual有这样的话:

el view.el

[...] this.el is created from the view's tagName, className, id and attributes properties, if specified. If not, el is an empty div.

所以在你看来是这样的:

tagName: 'li'

表示Backbone会自动创建一个新的<li>元素作为 View 的 el .

关于javascript - 未捕获的类型错误 : Cannot call method 'replace' of undefined backbone. js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14826149/

相关文章:

javascript - 使用 jquery/ajax 自动刷新特定 div 并加载图像

c++ - 共享指针可以调用函数模板参数吗

javascript - 从脚本中删除调试器行

javascript-events - 选中了多少个复选框

javascript - jQuery each() 循环迭代次数超过预期

javascript - MouseDown 事件不适用于整个容器

javascript - 更改按钮值 Onclick

javascript - 将html内容添加到js生成的类中

c++ - 将二进制数据转换为可打印的十六进制

c++ - 实例化一个类模板并调用它的方法