2014-02-17 48 views
0

作爲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元素,比如說,一個簡單的div,id =「the-plan」。問題是,「#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

更改渲染功能:

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

這做的伎倆(幾乎)。我只需要將'this.collection.models.each(function(item))'改成'this.collection.each(function(item))'。但是,我不知道爲什麼?有人可以評論這些代碼嗎? – Bunjip

+0

你可以看一下文檔http://backbonejs.org/#Collection-Underscore-Methods,所以當你調用'this.collection.each'時,你正在遍歷集合模型。 –

+0

是的,我已經有了這部分代碼。但是,我指的是你的原始答案。我沒有真正瞭解render()和renderPlanItem()函數中會發生什麼...... – Bunjip