2014-06-18 27 views
1

我的模板數據,暫且,編程設置的內容,使用POJO,與一些常數值:使用POJO來初始化ArrayController

var DROPDOWN_MENU = [ 
    { 'text' : 'Profile', 'icon' : 'fa fa-eye dd-icon',  'href' : '/profile' }, 
    { 'text' : null }, 
    { 'text' : 'Logout', 'icon' : 'fa fa-signout dd-icon', 'href' : '/signup/clear_session_and_logout' }, 
]; 

下面的模板:

<a class="dropdown-toggle opener" {{bind-attr id="elId"}} data-toggle="dropdown"> 
    <i {{bind-attr class="myclass"}}></i> 
</a> 
<ul class="dropdown-menu" role="menu"> 
    {{#each entry}} 
     {{#if entry.text}} 
      <li role="presentation"><a role="menuitem" tabindex="-1" href="{{entry.href}}"><i class="{{entry.icon}}"></i>{{entry.text}}</a></li> 
     {{else}} 
      <li role="presentation" class="divider"></li> 
     {{/if}} 
    {{/each}} 
</ul> 

以下控制器:

App.DropdownController = Ember.ArrayController.extend({ 
    elId : CNST.DROPDOWN_ELID, 
    content : DROPDOWN_MENU, 
    myclass : 'fa fa-power-off fa-2x', 
}); 

和以下觀點:

App.DropdownView = Ember.View.extend({ 
    templateName: 'navbar/dropdown', 
    controller: App.DropdownController, 
    didInsertElement: function() { 
     var controller = this.get('controller'); 
     var elId = controller.get('elId'); 
     if (DEBUG) { console.log('DropdownView.didInsertElement > activating dropdown for elId=%s', elId); } 
     $('#' + elId).dropdown(); 
    } 
}); 

但模板無法訪問由POJO定義的內容(因爲它不是ObjectArray?)。如何使用POJO中的數據強制我的ArrayController中的內容?

+0

你有什麼理由爲什麼你使用視圖和控制器來實現這個目標?一個組件看起來更自然。 – bguiz

回答

1

如果你是開放的使用組件,而不是在任何JavaScript:

var DROPDOWN_MENU = [ 
    { 'text' : 'Profile', 'icon' : 'fa fa-eye dd-icon',  'href' : '/profile' }, 
    { 'text' : null }, 
    { 'text' : 'Logout', 'icon' : 'fa fa-signout dd-icon', 'href' : '/signup/clear_session_and_logout' }, 
]; 

App.MyDropdownComponent = Ember.Component.extend({ 
    elId : CNST.DROPDOWN_ELID, 
    menu : DROPDOWN_MENU, 
    myclass : 'fa fa-power-off fa-2x', 
    didInsertElement: function() { 
     var elId = this.get('elId'); 
     if (DEBUG) { 
      console.log('DropdownView.didInsertElement > activating dropdown for elId=%s', elId); } 
     $('#' + elId).dropdown(); 
    } 
}); 

,並指定和相應的模板,在app/components/my-dropdown.hbs

<a class="dropdown-toggle opener" {{bind-attr id="elId"}} data-toggle="dropdown"> 
    <i {{bind-attr class="myclass"}}></i> 
</a> 
<ul class="dropdown-menu" role="menu"> 
    {{#each entry in menu}} 
     {{#if entry.text}} 
      <li role="presentation"><a role="menuitem" tabindex="-1" href="{{entry.href}}"><i class="{{entry.icon}}"></i>{{entry.text}}</a></li> 
     {{else}} 
      <li role="presentation" class="divider"></li> 
     {{/if}} 
    {{/each}} 
</ul> 

你可以把它進一步通過指定classNames而不是在模板中手動綁定它們。見customising class names

此外,不是像上面那樣對相同的POJO進行硬編碼,而是可以傳入您喜歡的任何值。請參閱customising attributes

+0

謝謝,這工作完美! – dangonfast