I want sibling Ember.js components to talk to each other so that, for example, only one component would be in an active state at any given time.
我希望兄弟Ember.js组件能够相互通信,以便例如在任何给定时间只有一个组件处于活动状态。
1 个解决方案
#1
1
One useful pattern for handling this is to introduce an attribute on the invoking controller or component which remembers which child component is active, pass that to the component, and then check in the component to see if that attribute is itself:
处理此问题的一个有用模式是在调用控制器或组件上引入一个属性,该属性会记住哪个子组件处于活动状态,将其传递给组件,然后检入组件以查看该属性是否为自身:
PARENT CONTROLLER AND TEMPLATE
父母控制器和模板
// 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}}
INDIVIDUAL ITEM COMPONENT LOGIC AND TEMPLATE
个人项目组成逻辑和模板
// 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>
#1
1
One useful pattern for handling this is to introduce an attribute on the invoking controller or component which remembers which child component is active, pass that to the component, and then check in the component to see if that attribute is itself:
处理此问题的一个有用模式是在调用控制器或组件上引入一个属性,该属性会记住哪个子组件处于活动状态,将其传递给组件,然后检入组件以查看该属性是否为自身:
PARENT CONTROLLER AND TEMPLATE
父母控制器和模板
// 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}}
INDIVIDUAL ITEM COMPONENT LOGIC AND TEMPLATE
个人项目组成逻辑和模板
// 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>