niran
niran

Reputation: 1980

Uncaught TypeError: Cannot call method 'toJSON' of undefined

I am getting following error in Backbone.JS,

Uncaught TypeError: Cannot call method 'toJSON' of undefined.

Here is the code for model and View,

 <script src="js/underscore.js"></script>
     <script src="js/jquery-1.6.2.min.js"></script>
    <script src="js/backbone.js"></script>

    var Person = Backbone.Model.extend({
            defaults:{
                name:"niran",
                age:20
            },
            validate:function(attr){
                if(attr.age <0){
                    return "should be greater than 0";
                }
            }
        }
    )

    var PhotoSearch = Backbone.View.extend({
        tagName:"li",
        initialize:function(){
            console.log(this.model)
            this.render();
        },

        template:_.template("<%= name %>(<%= age %>"),

        render:function(){
            this.$el.html(this.template(this.model.toJSON()));
        }
    });
       var p = new Person();
    var ps = new PhotoSearch({model:p});

any idea on this

Thanks all

Upvotes: 1

Views: 4200

Answers (2)

Jason Evans
Jason Evans

Reputation: 29186

Try this:

var PhotoSearch = Backbone.View.extend({
        tagName:"li",
        initialize:function(){
            _.bindAll(this, "render");
            console.log(this.model)
            this.render();
        },

        template:_.template("<%= name %>(<%= age %>"),

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

You're missing a call to _.bindAll(this, "render"); Without this call, this will not be set to the context of the view, which means that .model will be undefined.

You could also use _.bindAll(this); to bind all methods.

why do bindAll in backbone.js views?

Upvotes: 1

Magus
Magus

Reputation: 15104

According to the Backbone.js documentation ( http://backbonejs.org/ ), you need json2.js.

Upvotes: 1

Related Questions