Nie potrzeba używać EventEmitters wstawek.
Proste demo:
import EventEmitter from 'EventEmitter';
let x = new EventEmitter();
function handler(arg) {
console.log(`event-name has occurred! here is the event data arg=${JSON.stringify(arg)}`);
}
x.addListener('event-name', handler);
x.emit('event-name', { es6rules: true, mixinsAreLame: true });
Pełne podpis addListener
przyjmuje trzy argumenty:
EventEmitter.addListener(eventName, handler, handlerContext)
w komponencie reagować, prawdopodobnie chcesz użyć tego argumentu kontekstowe, tak, że handler może być metoda klasy zamiast funkcji inline i nadal zachowuje this == component instance
. Np .:
componentDidMount() {
someEmitter.addListener('awesome', this.handleAwesomeEvents, this);
// the generalist suggests the alternative:
someEmitter.addListener('awesome', this.handleAwesomeEvents.bind(this));
}
handleAwesomeEvents = (event) => {
let awesomeness = event.awesomeRating;
// if you don't provide context in didMount,
// "this" will not refer to the component,
// and this next line will throw
this.setState({ awesomeness });
};
FYI: Mam to od patrzenia na zdecydowanie unmagical realizacji the infamous Subscribable mixin. Wyniki wyszukiwania Google to w zasadzie komora echa z demo Ramsaya opartego na jednym mixinie.
P.S. Jeśli chodzi o wystawienie tego emitera na inny komponent, prawdopodobnie zapewniłbym, że składnik będący właścicielem dostarcza funkcję do odbierania referencji emitera, a komponent, który tworzy emiter, warunkowo wykonałby ten rekwizyt z emiterem.
// owner's render method:
<ThingThatEmits
onEmitterReady={(emitter) => this.thingEmitter = emitter}
/>
// inside ThingThatEmits:
componentDidMount() {
this.emitter = new EventEmitter();
if(typeof this.props.onEmitterReady === 'function') {
this.props.onEmitterReady(this.emitter);
}
}
Tutaj ktoś sugeruje użycie po prostu użyć „stary sposób” pisania części: http://hi-tips.tumblr.com/post/137014836571/use-eventemitter-for-calling-child-component -event Mam ten sam problem i chciałbym się dowiedzieć, czy jest jakiś właściwy sposób wykonania tego w ES6 –
Nadal tego szukam. Nie chcę zaczynać używania "react-mixin". – Tom