我希望兄弟Ember.js组件能够相互通信,以便例如在任何给定时间只有一个组件处于活动状态。
答案 0 :(得分: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>