Skip to content

Instantly share code, notes, and snippets.

@elgamine-dev
Forked from minwe/EventSystem.js
Last active June 24, 2016 21:51
Show Gist options
  • Save elgamine-dev/d691703bd318f14e59da1d25adccee16 to your computer and use it in GitHub Desktop.
Save elgamine-dev/d691703bd318f14e59da1d25adccee16 to your computer and use it in GitHub Desktop.
Global event system for React.js
let EventSystem = (function() {
this.queue = {};
return {
publish: (event, data) => {
let queue = this.queue[event];
if (typeof queue === 'undefined') {
return false;
}
while(queue.length > 0) {
(queue.shift())(data);
}
return true;
},
subscribe: (event, callback) => {
if (typeof this.queue[event] === 'undefined') {
this.queue[event] = [];
}
this.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
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment