0
我想讓兄弟Ember.js組件相互交談,以便在任何給定時間只有一個組件處於活動狀態。Ember.js中的同級組件如何彼此交談?
我想讓兄弟Ember.js組件相互交談,以便在任何給定時間只有一個組件處於活動狀態。Ember.js中的同級組件如何彼此交談?
處理這種情況的一種有用模式是在調用控制器或組件上引入一個屬性,該屬性可記住哪個子組件處於活動狀態,並將其傳遞給組件,然後檢入組件以查看該屬性是否屬於自己:
父控制器與模版
// 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>