0

Am new to backbone.js and having problem with the view render part. please find the code below , am unable to print li inside the ul.Html part is given below

<ul id="listview"></ul>
<script type="text/template" id="item">
  <li><%= author %></li>
</script>

and the js part

var book = Backbone.Model.extend();
var cols = Backbone.Collection.extend({
    model:book,
    url:"http://localhost/bbq/books.php"
});

var col  = new cols();
var view = Backbone.View.extend({

 el:'#listview',
 initialize:function () {
     _.bindAll(this, "render"); 
     this.model.fetch({
        success:this.render  
    });
 }, 

 render: function () {
      _.each(this.model.models, function (mode) {
          $(this.el).append( new listUsers({model:mode}).render.el );
     },this);
     return this;
 }

});

var listUsers = Backbone.View.extend({
   template: _.template($('#item').html()),
   render:function () {  
     $( this.el ).html( this.template( this.model.toJSON() ) );  
     return this;
   }
});
var vieb = new view({ model : col });
1
  • I have been seeing this $(this.el).append( new listUsers({model:mode}).render.el pattern in so many questions... may I know from where you're learning this..?
    – T J
    Dec 21, 2015 at 12:24

1 Answer 1

1

One issue is that you are not invoking the render method of child views.

Change

$(this.el).append( new listUsers({model:mode}).render.el

to

$(this.el).append( new listUsers({model:mode}).render().el

Your code can be better written as follows:

var Book = Backbone.Model.extend();
var Books = Backbone.Collection.extend({
  model: Book,
  url: "http://localhost/bbq/books.php"
});
var ListUsers = Backbone.View.extend({
  template: _.template($('#item').html()),
  initialize: function() {
    this.render();
  },
  render: function() {
    this.$el.html(this.template(this.model.toJSON()));
    return this;
  }
});

var Booksview = Backbone.View.extend({
  el: '#listview',
  initialize: function() {
    _.bindAll(this, "render");
    this.collection.fetch({
      success: this.render
    });
  },
  render: function() {
    this.collection.each(function(model) {
      this.$el.append(new ListUsers({
        model: model
      }).el);
    }, this);
    return this;
  }
});

var books = new Books();
var view = new Booksview({
  collection: books
});
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.