骨幹

2012-10-17 227 views
1

渲染的集合我有一個模型的工作該做這個看起來像這樣骨幹

collection= 
{ 
foo:[ [1,1], [2,2], [3,3] ] 
bar: [ [1,1], [2,2], [3,3] ] 
} 

我呈現了這一點,以查看主幹:第一

template: JST["backbone/templates/first"] 
collection.each (data) -> 
     foo = data.attributes.foo 
     bar = data.attributes.bar 
     for foos in foo 
     view = new Traveltime.Views.ViewExtractTimeList(model: foos) 
     $('ul.listcontainer').append(view.render().el) 
     for bars in bar 
     console.log perce 
     view = new Traveltime.Views.ViewExtractPercentList(model: bars) 
     $('ul.2ndlistcontainer').append(view.render().el) 

模板:

<ul class="listcontainer"> 
</ul> 

<ul class="2ndlistcontainer"> 
</ul> 

然後,我有2個更多的意見處理每個獨立的臨時:

class App.Views.ViewExtractFoo extends Backbone.View 

    tagName: "li" 
    template: JST['backbone/templates/foo'] 

    render: -> 
    $(@el).html(@template(content: @model)) 
    this 


class App.Views.ViewExtractBar extends Backbone.View 

    tagName: "li" 
    template: JST['backbone/templates/bar'] 

    render: -> 
    $(@el).html(@template(content: @model)) 
    this 

模板看起來像這樣(交換FOO的棒條爲例):

<li> 
Foo: <%=content.attributes.foo%> 
</li> 

現在這個工作,而且效果很好。但它感覺真的很混亂。我在rails中使用backbone,所以像6個或更多的不同文件只需要一個JSON請求並渲染它。它感覺討厭,有更好的方法。我只是不確定它是哪一個。

我只是想,如果我在Rails中做了這個,我可以有一個看法可以把這一切都拿出來!?

我可以使用collection.each並以某種方式將嵌套集合傳遞給模板嗎?

位卡在這裏,我絕不擅長這一點,所以任何幫助很大。

+0

有什麼我可以添加幫助嗎?對我來說,這似乎很漫長 –

回答

0

簡化和統一您的模板和視圖是一種選擇。模板可以使用json對象,所以它們可以渲染數組,這很適合渲染列表,就像你的情況一樣。例如,您可以只使用一個ListView爲使用單個模板的任何列表執行實際呈現,然後在您的主視圖中重複使用此視圖獲取集合對象的兩個屬性。希望下一個例子能讓你瞭解你在哪裏以及如何簡化。

class ListView extends Backbone.View 
    tagName: 'ul' 
    template: """ 
     {{#items}} 
      <li>{{content}}</li> 
     {{/items}} 
    """ 
    render: -> 
     @$el.html @template items: @options.items 
     @ 

class MainView extends Backbone.View 

    render: -> 
     @$el.empty() 
     for own subitems of @options.items 
      @$el.append new ListView items: subitems 
     @ 



# Example usage # 
collection = 
    foo: [[1,1], [2,2], [3,3]] 
    bar: [[1,1], [2,2], [3,3]] 

$('body').append new MainView(items: collection).render().$el