Skip to content

Instantly share code, notes, and snippets.

@minwe
Forked from yitsushi/EventSystem.js
Last active October 22, 2019 03:03
Show Gist options
  • Save minwe/14a62f0eb5e865fef078 to your computer and use it in GitHub Desktop.
Save minwe/14a62f0eb5e865fef078 to your computer and use it in GitHub Desktop.
Global event system for React.js
var EventSystem = (function() {
var self = this;
self.queue = {};
return {
publish: function (event, data) {
var queue = self.queue[event];
if (typeof queue === 'undefined') {
return false;
}
while(queue.length > 0) {
(queue.shift())(data);
}
return true;
},
subscribe: function(event, callback) {
if (typeof self.queue[event] === 'undefined') {
self.queue[event] = [];
}
self.queue[event].push(callback);
}
};
}());
var RiskList = React.createClass({
getInitialState: function() {
return { risks: [] };
},
componentDidMount: function() {
// someting
},
render: function() {
EventSystem.publish('risk.count.update', this.state.risks.length);
// something
}
}
var RiskPage = React.createClass({
updateRiskCount: function(count) {
this.setState({
riskCount: count
});
},
componentDidMount: function() {
EventSystem.subscribe('risk.count.update', this.updateRiskCount);
},
getInitialState: function() {
return {
riskCount: 0
};
},
render: function() {
// something
}
});
@sjasthi16
Copy link

Is this working for anyone?

@24HOURSMEDIA
Copy link

nice simple event dispatcher. unsubscribe must be implemented indeed to avoid leaks

@simonberger
Copy link

simonberger commented Jul 21, 2017

It works fine, is simple and enough for most requirements. One doesn't always need a bloated package.
Added unsubscribe and changed to class. Easily addable to browserify:

https://gist.github.com/simonberger/13d3a416cdf3e72b5a46b031a9fb997d

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