2015-07-11 58 views

回答

1

处理这种情况的一种有用模式是在调用控制器或组件上引入一个属性,该属性可记住哪个子组件处于活动状态,并将其传递给组件,然后检入组件以查看该属性是否属于自己:

父控制器与模版

// thing/controller.js 

// Remember which item is active. 
// This will be changed by changeActive action, and passed to components. 
activeItem: null, 

actions: { 
    // Change active item. Passed to component as handler for 'action'. 
    changeActive(item) { this.set('activeItem', item); } 
} 
{{! thing/template.js }} 

{{#each items as |item|}} 
    {{item-component item=item active=activeItem action='changeActive'}} 
{{/each}} 

单项组件逻辑与模版

// components/item-component/component.js 

// Give this component a disabled class if not the active item. 
classNameBindings: ['isMe'::disabled'], 

// Current active item--passed as attribute. 
active: null, 

// Check is I am the active item. 
isMe: Ember.computed('active', function() { 
    return this === this.get('active'); 
}), 

// Advise upstream that I have become active. 
actions: { 
    select() { this.sendAction('action', this); } 
} 
{{! components/item-component/template.js }} 

Hello, I am item {{item.name}}. 
<span {{action 'select'}} Select me.</span>