backbone.js 集合视图中的渲染模型视图不知道其元素?

wtlkbnrh  于 2022-11-10  发布在  其他
关注(0)|答案(1)|浏览(151)

作为Backbone.js的新手,我尝试按照Addy Osmani的“开发Backbone.js应用程序”来开发SPA。它的练习2(http://addyosmani.github.io/backbone-fundamentals/#exercise-2-book-library--a 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);

这是怎么了?

cgyqldqp

cgyqldqp1#

将渲染函数更改为:

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();
}

相关问题