Serdar Dogruyol
Serdar Dogruyol

Reputation: 5157

Backbone Collection Cant Find Model's View Render

I'm trying to render a simple collection view and having a weird issue.

The problem is that when i try to call the render method of the model in a collection's view it can't find the render method.

My Model And View

var PersonModel = Backbone.Model.extend({});

var PersonView = Backbone.View.extend({
tagName : "person",
events:{
    "click h3":"alertStatus"

},
initialize:function(){
    this.model.on('change',this.render,this);

} ,
render:function(){

    var underscore_template = _.template('<h3>Name : <%= name %></h3>'+
        '<h3>Last Name : <%= surname %></h3>' +
        '<h3>Email : <%= email %> </h3>') ;

    console.log("Person View Render Oldu");
    this.$el.html(underscore_template(this.model.toJSON()));

},
alertStatus :function(e){
    alert("Clicked on Model View");
}
});

My Collection And Collection View

var PersonList = Backbone.Collection.extend({
model:PersonModel,
url:'/models'
});

var personList = new PersonList();

var PersonListView = Backbone.View.extend({
tagName : "personlist",
render : function(){
    this.collection.forEach(this.addOne,this);
},
addOne : function(personItem){
    var personView = new PersonView({model:personItem});
    this.$el.append(personView.render().el);  // The call to personView.render throws undefined
},
initialize : function(){
    this.collection.on('add',this.addOne,this);
    this.collection.on('reset',this.addAll,this);
},
addAll : function(){
    this.collection.forEach(this.addOne,this);
}
});

var personListView = new PersonListView({
collection:personList
});


personList.fetch({
success:function(){
    console.log("Fetch success");
}
});

I'm calling this JS on document ready with Jquery and adding it to a div with id named app.

My fetch is also successful.The problem persists at the addOne function of the Collection View when trying to call personView.render().el

Any help would be appreciated.

Upvotes: 0

Views: 294

Answers (1)

Meta
Meta

Reputation: 346

You forgot returning the element in your render:

render : function() {

    var underscore_template = _.template('<h3>Name : <%= name %></h3>'+
        '<h3>Last Name : <%= surname %></h3>' +
        '<h3>Email : <%= email %> </h3>') ;

    console.log("Person View Render Oldu");
    this.$el.html(underscore_template(this.model.toJSON()));

    return this;  // chaining
}

Otherwise you can't chain it and you can't access el afterwards.

Upvotes: 1

Related Questions