1

My collection is not rendering for some reason. Cannot find out why.

TreeItem = Backbone.Model.extend({

});

TreeList = Backbone.Collection.extend({
  model: TreeItem,
  url: "/get_tree_list"
});

window.tree_list = new TreeList();

// VIEW

window.TreeItemView = Backbone.View.extend({
  tagName: 'li',
  initialize: function(){
    _.bindAll(this, 'render');
  },
  render: function(){
    $(this.el).html('<span>'+this.model.get('title')+'</span>');
    return this;
  }
});

window.TreeListView = Backbone.View.extend({
  el: "#tree-structure",
  events: {

  },
  initialize: function() {
    _.bindAll(this, 'appendItem', 'render');
    tree_list.bind('add', this.appendItem);
    tree_list.fetch();
    this.render();
  },
  render: function() {
    tree_list.each(this.appendItem);
    return this;
  },
  appendItem: function(item){
    var tree_item_view = new TreeItemView({
      model: item
    });
    $(this.el).append(tree_item_view.render().el);

  }
});

var tree_list_view = new TreeListView;
1
  • Do you get some sort of error? Or does it fail silently? Commented May 16, 2012 at 4:27

1 Answer 1

2

Backbone.js provides a lot to be interpreted that's where people new go wrong. Your mistake is fundamental in nature. You tie the View directly to the model

  • see initialize function where a instance of collection is rendered!!

  • Always and anywhere you create model, collection pass then as parameters to the constructor of views. Check my fiddle

  • Never call render inside model, view or collection. They must be inside application file

JsFiddle

http://jsfiddle.net/35QGM/

Sign up to request clarification or add additional context in comments.

3 Comments

+1 for the explanation and for the running code example, but I'm more flexible about the points you describe, they are good practices but I would not prefix them with "Always" neither "Never".
@fguillen thanks :) just giving sense of direction to Min. Later when he understands he will know of different ways to do it
Thanks for the 'mini-tutorial'. That helps!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.