簡體   English   中英

Backbone.js未捕獲的TypeError

[英]Backbone.js Uncaught TypeError

我寫了流動的backbone.js程序:

<script>

        var PostModel = Backbone.Model.extend();
        var PostView = Backbone.View.extend({
           template: _.template($('#posttemplate').html()),
           intialize: function() {
              console.log("intializing view");
           },
           render: function() {
              console.log("rendering..");
              var htmloutput = this.template(this.model.toJSON());
              $('#postcontainer').html(htmloutput);
              return this;
           }
        });         

       $(document).ready(function() {
           var postmodel = new PostModel({title: "hello"});
           var postview = new PostView({model: postmodel});
           postview.render();
        });


    </script type="text/javascript">



<script type="text/template" id="posttemplate">
        <div> Title: <%= title %> , post: <%= post %> </div>
</script>

<div class="container" id="postcontainer"></div>

當我運行代碼時,我收到以下錯誤:

未捕獲的TypeError:無法讀取未定義的屬性'replace'

但是當我把template = _.template($('#posttemplate')。html());它完全正常。 進入渲染功能。

您的問題是您在模板存在之前嘗試訪問該模板。 HTML文檔從頂部到底部進行解析

template: _.template($('#posttemplate').html())

然后$('#posttemplate')選擇器不返回任何結果,因為尚未解析包含模板的元素。

試着移動

<script type="text/template" id="posttemplate">
        <div> Title: <%= title %> , post: <%= post %> </div>
</script>

元素高於您的第一個腳本元素。

將它放入render函數時它起作用的原因是在文檔觸發就緒事件之后調用render ,此時模板存在。

暫無
暫無

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

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