Backbone.js not rendering

人盡茶涼 提交于 2020-01-15 12:02:53

问题


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:


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/



来源:https://stackoverflow.com/questions/10611977/backbone-js-not-rendering

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!