0
votes

Im new in backbone Im currently learning about templates however I have this output error Uncaught TypeError: Cannot read property 'replace' of undefined underscore.js:1305 _.template underscore.js:1305 (anonymous function)

Here is my index.js

var Person = Backbone.Model.extend({

    defaults: {
        name: 'ozan onder',
        age: 20,
        occupation: 'worker'
    }
});

var PersonView = Backbone.View.extend({
    //by default the tagname is a div element
    //but we will override it
    tagName: 'li',

    //% is how can access to a property name
    // create templer
    template: _.template($('#personTemplate').html()),

    initialize: function() {
        this.render();
    },

    render: function() {
        //set the html
        this.$el.html(this.template(this.model.toJSON()));
    }

});

var person = new Person;
var personView = new PersonView({ model: person });

console.log(personView.el);

And here is my index.html

<!DOCTYPE html>
<html> 
  <head> 
    <!--this import order is important-->
    <script src="../../library/jquery-1.8.2.min.js"></script>
    <script src="../../library/underscore.js"></script>
    <script src="../../library/backbone.js"></script>
    <script src="index.js"></script>

  </head>

  <body>

    <script id="personTemplate" type="text/template">
        <strong><%= name %></strong> (<%= age %>) - <%= occupation %>

    </script>

  </body>

</html>  
1
Make sure you are wrapping your code in a jQuery ready func so that it doesn't fire until your page is loaded. Perhaps you are acting on a DOM element that does not exist when your code initializes. - james emanon
Thanksss a lottttt:) - ozimax06
@jamesemanon could you please provide that in the form of an answer so that it can be accepted? Otherwise this question will languish in SO' unanswered questions queue forever :-) - machineghost
Ok, I will right now. thanks - james emanon

1 Answers

1
votes

Make sure you are wrapping your code in a jQuery ready func so that it doesn't fire until your page is loaded. Perhaps you are acting on a DOM element that does not exist when your code initializes.

$( document ).ready(function() {
   // put your code here
});

OR - They both accomplish the same thing.


$(function() {
  // put your code here
});