2016-01-25 114 views
0

我需要在餘燼中創建左側導航欄,其功能非常類似於ember website上的左側導航欄。我目前在Ember 1.X上嵌套JSON的序列化支持很差。我開始了與這個數據模型,我不相信會與Ember 1.X工作:Ember左側導航創建

var menuItems = [{ 
    id: 1, 
    title: 'Payroll', 
    children: { 
     'Child 1', 
     'Child 2' 
    } 
    },{ 
    id: 2, 
    title: 'Time & Attendance', 
    children: { 
     'Child 1', 
     'Child 2', 
     'child 3' 
    } 
}]; 

當我建立這個模型我得到一個語法錯誤:

Unexpected token

title: 'Payroll', 
children: { 
      'Child 1', //There's an arrow pointing to the ',' here 
      'Child 2' 
},{ 

爲什麼我會得到這個錯誤?

我有我的菜單template.js建成像這樣(*未經):

<div class="container-fluid"> 
    <div class="row"> 
    <div class="col-md-2"> 
     <ul class="navMenu nav list-unstyled"> 
      {{#each model as |menuItem|}} 
      {{#if isActive}} 
       <span {{action "makeInactive"}} class="">{{menuItem.title}}</span> 
       <ul> 
       {{#each child as |children|}} 
        <li><a href="#">{{child}}</a></li> 
       {{/each}} 
       </ul> 
      {{else}} 
       <span {{action "makeActive"}} class="">{{menuItem.title}}</span> 
      {{/if}} 
      {{/each}} 
     </ul> 
    </div> 
    <div class="col-md-10">Will be content</div> 
    </div> 
</div> 

這將排序的工作,但我需要一些方法,以確保只有1元是活動的時間。

我需要更新到燼2.X做這樣的事情嗎?

回答

1

我不認爲你需要這個燼2。我建議將'selected'屬性添加到您的模型中,或者使用Ember.ProxyObject爲每個menuItem對象添加一個名爲'selected'的額外屬性,以便我們可以捕獲哪個屬於活動狀態,然後執行以下操作:

您的模板看起來像:

<div class="container-fluid"> 
    <div class="row"> 
    <div class="col-md-2"> 
     <ul class="navMenu nav list-unstyled"> 
      {{#each menuItems as |menuItem|}} 
       <span {{action "toggleActive" menuItem}} class="">{{menuItem.title}}</span> 
       {{#if menuItem.selected}} 
        <ul> 
        {{#each menuItem.children as |child|}} 
         <li><a href="#">{{child}}</a></li> 
        {{/each}} 
        </ul> 
       {{/if}} 
      {{/each}} 
     </ul> 
    </div> 
    <div class="col-md-10">Will be content</div> 
    </div> 
</div> 

和你的控制器看起來像:

menuItems : Ember.computed.map('model', function(menuItem, index) { 
    if(menuItem.get('childItems.length')){ 
     return Ember.ObjectProxy.create({ 
      content: menuItem, 
      selected: false 
     }); 
    } 
}), 

actions:{ 
    toggleActive: function(menuProxy){ 
     this.get('menuItemsProxy').setEach('selected', false); 
     menuProxy.set('selected', true); 
    } 
} 

UPDATE

很多燼數據已經改變,但這給一試:

//assuming you are using ember cli 
export default Ember.Model.create({ 
    title:DS.attr('string'), 
    childItems: DS.hasMany('menuItem', {async: true}) 
}); 

和菜單項API的JSON的反應應該是:

{ 
    "menuItems": [ 
     { 
      id: 1, 
      title: 'Payroll', 
      childItems: [3, 4] 

     }, { 
      id: 2, 
      title: 'Time & Attendance', 
      children: [5, 6] 
     }, 
     { 
      id: 3, 
      title: 'child of payroll', 
      childItems: [] 
     },... 
    ] 
} 
+0

這是在很多方面有幫助。我更新了這個問題,因爲我的模型給了我一個語法錯誤。我認爲這個錯誤是由於Ember 1.X無法處理我定義的嵌套模型。我必須通過這個錯誤來試試這個。我應該在原來的問題中提到這一點。 –

+0

我已經更新了我的答案,也許這會有所幫助 - 因爲我還沒玩過相當多的燼數據。 –