简体   繁体   English

同级组件如何在Ember.js中相互通信?

[英]How can sibling components to talk to each other in Ember.js?

我希望同级的Ember.js组件能够互相通信,例如,在任何给定时间,只有一个组件处于活动状态。

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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM