集合视图中的渲染模型视图不知道它的元素?

时间:2014-02-17 20:54:29

标签: javascript backbone.js backbone-views

作为Backbone.js的新手,我尝试开发SPA,其中包括Addy Osmani的“开发Backbone.js应用程序”。练习2(http://addyosmani.github.io/backbone-fundamentals/#exercise-2-book-library---your-first-restful-backbone.js-app)显示了如何使用集合视图从每个集合对象渲染内部模型视图。但是,此示例中的集合视图没有自己的html标记。因此,集合的模型与集合视图的DOM元素相关联(此处:'#books')。我想使用自己的模板来首先渲染我的集合视图的html元素,比如一个id =“the-plan”的简单div。问题是,“#the.plan”无法从内部模型视图中识别为元素属性。因此,内部视图根本不会呈现。没有错误消息,并且所有console.log都正常工作。代码看起来像这样:

app.PlanItemView = Backbone.View.extend({
  className: "plan-item",
  template: _.template($("#plan-item-view-template").html()),

  render: function(){
    console.log("Rendering plan item view...");
    this.$el.append(this.template(this.model.toJSON()));
    return this;
  }
});

app.PlanView = Backbone.View.extend({
  el: ".main-panel",
  id: "#the-plan",
  template: _.template($("#plan-view-template").html()),

  initialize: function(initialPlanItems){
    console.log("Plan View initialized... Selector: " + this.id);
    console.log("Incoming initial plan item data: " + _.first(_.values(_.first(initialPlanItems))));
    this.collection = new app.MealPlan(initialPlanItems);
    this.render();
  },

  // render plan by rendering each item in its collection
  render: function() {

    this.$el.append(this.template({
      "myPlan": this.collection.each(function(item){
      this.renderPlanItem(item);
    }, this)
    }));

    return this;
  },

  // render a plan item by creating a PlanItemView and appending the
  // element it renders to the plan's id-element ('#the-plan')
  renderDish: function(item){
      var planItemView = new app.PlanItemView({
          model: item,
          el: this.id
      });
      this.$("#the-plan").append(planItemView.render());
  }
});

...

var planView = new app.PlanView(test_plan_items);

这里有什么问题?

1 个答案:

答案 0 :(得分:1)

将渲染功能更改为:

render: function() {

    this.$el.append(this.template({
      "myPlan": this.collection
    }));

    this.collection.each(function(item){
      this.renderPlanItem(item);
    }, this);

    return this;
}

并将renderDish更改为:

renderPlanItem: function(item){
    var planItemView = new app.PlanItemView({
        model: item,
        el: this.id
    });
    planItemView.render();
}