简体   繁体   中英

Backbone.js Uncaught TypeError

I have written the flowing backbone.js program :

<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>

when i run the code i get the following error:

Uncaught TypeError: Cannot read property 'replace' of undefined

but it works perfectly fine when i put template = _.template($('#posttemplate').html()); into the render function.

Your problem is that you're trying to access the template before it exists. The HTML document is parsed from the top to the bottom and when you have

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

then the $('#posttemplate') selector does not return any results because the element containing the template hasn't been parsed yet.

Try moving the

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

element up above your first script element.

The reason it works when you put it in the render function is that render is called after the document fires a ready event, at which point the template exists.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM