Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

template not loading in backbone.js ( TypeError: text is undefined )

I'm learning backbone.js and I'm pretty much in the beginning. I want to add a template through underscore template method but it's not working for me. I searched for this error but couldn't fix it myself. How can I move forward if it's not showing the template. Need some help guys.

Here is the code (this code is from addyosmani's book backbone-fundamentals):

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>testing</title>
</head>
<body>
<script src="scripts/jquery.js"></script>
<script src="scripts/underscore.js"></script>
<script src="scripts/backbone.js"></script>
<script>


    var TodoView = Backbone.View.extend({
    tagName: 'li',
    // Cache the template function for a single item.
    todoTpl: _.template( $('#item-template').html() ),

    events: {
    'dblclick label': 'edit',
    'keypress .edit': 'updateOnEnter',
    'blur .edit': 'close'
    },

    // Re-render the titles of the todo item.

    render: function() {
    this.$el.html( this.todoTpl( this.model.toJSON() ) );
    this.input = this.$('.edit');
    return this;
    },

    edit: function() {
    // executed when todo label is double clicked
    },

    close: function() {
    // executed when todo loses focus
    },

    updateOnEnter: function( e ) {
    // executed on each keypress when in todo edit mode,
    // but we'll wait for enter to get in action
    }

    });


    var todoView = new TodoView();
    // logs reference to a DOM element that cooresponds to the view instance
    console.log(todoView.el);
like image 613
Michael Avatar asked Dec 19 '12 11:12

Michael


2 Answers

If the template is defined after your script it will not work.

wrap your entry point into

$(function(){
   var todoView = new TodoView();
});

so you dont get this kind of error.

like image 122
mpm Avatar answered Jan 04 '23 04:01

mpm


I got the same error. Make sure that template with defined id exists on the page. In my case I used wrong id for template, and this was a reason of error "TypeError: n is undefined".

like image 27
yesnik Avatar answered Jan 04 '23 04:01

yesnik