簡體   English   中英

未捕獲的TypeError:無法調用未定義的ribs.js的方法“替換”

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

我正在嘗試使用Beta.js開發一個簡單的RSS應用程序。 我正在使用這個ribs.js 教程 在定義模板時,在第2行(模板)上出現以下錯誤。 誰能告訴我為什么在教程中定義了tagName:“ li”?

未捕獲的TypeError:無法調用未定義的ribs.js的方法“替換”

Javscript

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').html()時,如果DOM中沒有#tmpl_sourcelist ,則會發生這種情況。

有一些簡單的解決方案:

  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是從視圖的tagNameclassNameidattributes屬性(如果指定)創建的。 如果不是,則el為空div

因此,在您看來:

tagName: 'li'

表示Backbone將自動創建一個新的<li>元素作為視圖的el

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM