Backbone.js 未捕获的类型错误

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>

当我 运行 代码时,我得到以下错误:

未捕获的类型错误:无法读取未定义的 属性 'replace'

但是当我放的时候它工作得很好 模板 = _.template($('#posttemplate').html());进入渲染功能。

您的问题是您试图在模板存在之前访问它。 HTML 文档是从上到下解析的,当你有

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

然后 $('#posttemplate') 选择器不会 return 任何结果,因为包含模板的元素尚未被解析。

尝试移动

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

第一个脚本元素上方的元素。

将它放在 render 函数中时它起作用的原因是 render 在文档触发就绪事件后调用,此时模板存在。