Backbone.js Uncooked TypeError
I wrote a flowbone.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 fine when i template = _.template ($ ('# posttemplate'). html ()); into the render function.
source to share
Your problem is that you are trying to access the template before it exists. HTML document is parsed from top to bottom and when you
template: _.template($('#posttemplate').html())
then the selector $('#posttemplate')
does not return any results because the element containing the template has not yet been parsed.
Try to move
<script type="text/template" id="posttemplate">
<div> Title: <%= title %> , post: <%= post %> </div>
</script>
above your first script element.
The reason it works when you put it in a function render
is because render
it gets called after the document fires a prepared event, after which the template exists.
source to share