Skip to content

Instantly share code, notes, and snippets.

@simonberger
Forked from minwe/EventSystem.js
Last active March 11, 2021 13:00
Show Gist options
  • Save simonberger/13d3a416cdf3e72b5a46b031a9fb997d to your computer and use it in GitHub Desktop.
Save simonberger/13d3a416cdf3e72b5a46b031a9fb997d to your computer and use it in GitHub Desktop.
Global event system for React.js
class EventSystem {
constructor() {
this.queue = {};
}
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);
}
// the callback parameter is optional. Without it the whole event will be removed, instead of
// just one subscibtion. Enough for simple implementations
unsubscribe(event, callback) {
let queue = this.queue;
if (typeof queue[event] !== 'undefined') {
if (typeof callback === 'undefined') {
delete queue[event];
} else {
this.queue[event] = queue[event].filter(function(sub) {
return sub !== callback;
})
}
}
}
}
module.exports = new EventSystem();
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);
},
componentWillMount: function() {
EventSystem.unsubscribe('risk.count.update', this.updateRiskCount);
// Removes all subscriptions to this event. Would do same and simpler for this example
// EventSystem.unsubscribe('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