【问题标题】:uncaught TypeError: Cannot call method 'replace' of undefined backbone.js未捕获的TypeError:无法调用未定义的backbone.js的方法“替换”
【发布时间】:2013-01-27 09:09:28
【问题描述】:

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

未捕获的类型错误:无法调用未定义的方法“替换” 主干.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>

谢谢

【问题讨论】:

  • 尝试在没有数据的情况下运行模板,看看你会得到什么...this.$el.html(this.template())
  • 它在第 2 行出错(模板:_.template($('#tmpl_sourcelist').html()),)。不知道你推荐什么。

标签: javascript html templates backbone.js underscore.js


【解决方案1】:

你的错误就在这里:

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

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

_.template(undefined)

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

有几个简单的解决方案:

  1. 调整您的 &lt;script&gt; 顺序,以便在您尝试加载视图之前您的 #tmpl_sourcelist 出现。
  2. 在视图的initialize 中创建编译后的模板函数,而不是在视图的“类”定义中:

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

tagName 而言,fine manual 有这样的说法:

el view.el

[...] this.el 是从视图的 tagNameclassNameidattributes 属性(如果指定)创建的。如果不是,el 是一个空的div

所以在你看来:

tagName: 'li'

意味着 Backbone 将自动创建一个新的 &lt;li&gt; 元素作为您视图的 el

【讨论】:

  • 很好的答案!它在我的情况下帮助了我,因为 $("#target").html(_.template(template, [posts]));正在寻找一个 id = target 但它是一个类。
  • @Anthony:谢谢。所以同样的_.template(undefined)问题变相了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-02-23
  • 2012-08-27
  • 1970-01-01
  • 2014-09-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多