Skip to content

Instantly share code, notes, and snippets.

@zpao
Created January 9, 2014 23:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save zpao/8344371 to your computer and use it in GitHub Desktop.
Save zpao/8344371 to your computer and use it in GitHub Desktop.
var CustomEvents = (function() {
var _map = {};
return {
subscribe: function(name, cb) {
_map[name] || (_map[name] = []);
_map[name].push(cb);
},
notify: function(name, data) {
if (!_map[name]) {
return;
}
// if you want canceling or anything else, add it in to this cb loop
_map[name].forEach(function(cb) {
cb(data);
});
}
}
})();
// in <MyComponent>
CustomEvents.subscribe('foo', function(data) {
console.log('foo', data);
});
// in <SomeOtherComponent>
CustomEvents.notify('foo', {bar: 7});
@adelevie
Copy link

adelevie commented May 4, 2014

In which part of the component lifecycle would I put CustomEvents.subscribe? Anywhere? render?

@tarikjn
Copy link

tarikjn commented Feb 18, 2015

If using Browserify, Node event emitters is another option: http://nodejs.org/api/events.html

@EpokK
Copy link

EpokK commented Mar 25, 2015

@adelevie

For communication between two components that don't have a parent-child relationship, you can set up your own global event system. Subscribe to events in componentDidMount(), unsubscribe in componentWillUnmount(), and call setState() when you receive an event.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment