2012-09-17 64 views
0

我正在使用主幹和牽線木偶,我想根據數據中的變量來呈現視圖。 this.model.template我想可以從我的數據拉(返回myTemplate和myOtherTemplate),然後我可以在渲染功能做一些操作,但它不工作。有什麼建議麼?。該視圖可以讓人意識到該模型?根據數據中的變量分配視圖模板?

var graph = [{ 
    nodeName: "1st level item", 
    template: "myTemplate", 
    nodes: [{ 
     nodeName: "2nd level item", 
     template: "myOtherTemplate" 
    }] 
}]; 


TreeView = Backbone.Marionette.CompositeView.extend({ 
    tagName: "ul", 
    initialize: function(){ 
     this.collection = this.model.nodes; 
    }, 
    appendHtml: function(collectionView, itemView){ 
     collectionView.$("li:first").append(itemView.el); 
    }, 
    render: function(){ 
     var that = this; 
     console.log('Loading template name: ' + name + ' template: ' + this.template + ' data: ' + this.model.template); 
     TemplateManager.get(this.template, function(template){ 
      var html = $(template).tmpl(); 
      that.$el.html(html); 
     }); 
     return this; 
    } 
}); 
+0

我很難理解你的問題是什麼。該視圖可以讓人意識到該模型?當然:-)只要做:'this.model'從內部引用視圖的模型。除此之外,雖然我不明白你在問什麼。 – machineghost

+0

this.model.template返回undefined對我來說:( –

+0

this.model將是你傳遞給你的視圖的任何模型。因此,在你的代碼中的某個地方,你必須有'新的TreeView({...';裏面你可以使用elipsis定義一個模型,就像這樣:'new TreeView {model:new Backbone.Model(graph)' – machineghost

回答

2

你是如何初始化視圖的?

該視圖通常期望該模型是Backbone模型。訪問模型屬性時,應該使用mymodel.get('attributeName')。單個屬性不能直接在模型上使用。它們在mymodel.attributes(例如,mymodel.attributes.template)中可用,但不應直接使用attributes,因爲除非調試,否則屬性如何存儲和訪問可能會在將來發生變化,或者如果使用任何插件,可能會因各種插件而發生更改。

另請注意,在大多數情況下,您不應該覆蓋render方法。相反,看看beforeRenderonRender

相關問題