簡単なサービスを作成して使用できます
/** eventsService */
module.exports = {
callbacks: {},
/**
* @param {string} eventName
* @param {*} data
*/
triggerEvent(eventName, data = null) {
if (this.callbacks[eventName]) {
Object.keys(this.callbacks[eventName]).forEach((id) => {
this.callbacks[eventName][id](data);
});
}
},
/**
* @param {string} eventName name of event
* @param {string} id callback identifier
* @param {Function} callback
*/
listenEvent(eventName, id, callback) {
this.callbacks[eventName][id] = callback;
},
/**
* @param {string} eventName name of event
* @param {string} id callback identifier
*/
unlistenEvent(eventName, id) {
delete this.callbacks[eventName][id];
},
};
例(トリガーも同様)
import eventsService from '../../../../services/events';
export default class FooterMenu extends Component {
componentWillMount() {
eventsService
.listenEvent('cart', 'footer', this.cartUpdatedListener.bind(this));
}
componentWillUnmount() {
eventsService
.unlistenEvent('cart', 'footer');
}
cartUpdatedListener() {
console.log('cart updated');
}
}