12

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

未捕获的TypeError:无法调用未定义的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>

谢谢

4

1 回答 1

47

你在这里得到你的错误:

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

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

_.template(undefined)

如果#tmpl_sourcelist当您说 DOM中没有$('#tmpl_sourcelist').html().

有几个简单的解决方案:

  1. 调整您的<script>订单,以便您#tmpl_sourcelist在尝试加载视图之前到达。
  2. initialize在视图而不是视图的“类”定义中创建编译的模板函数:

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

就目前tagName而言,精美的手册是这样说的:

埃尔 view.el

[...]this.el是从视图的tagNameclassName和属性(如果指定id)创建的。attributes如果不是,则el为空div

因此,在您看来:

tagName: 'li'

意味着 Backbone 将自动创建一个新<li>元素作为您视图的el.

于 2013-02-12T06:02:01.837 回答