Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
EventSystem that I use with React.js to communicate between components
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
}
});
@antonioribeiro

This comment has been minimized.

Copy link

commented Nov 18, 2014

Cool, thanks for this!

But I found that you can only fire the event once, because somehow this:

  while(queue.length > 0) {
    (queue.shift())(data);
  }

Is removing something from the events array, so I had to:

  jQuery.each( queue, function( key, method ) {
    (method)(data);
  });
@simple17

This comment has been minimized.

Copy link

commented Apr 10, 2015

Or you can also subscribe on componentDidUpdate.

@binjospookie

This comment has been minimized.

Copy link

commented Feb 20, 2016

Is removing something from the events array, so I had to:
jQuery.each( queue, function( key, method ) {
(method)(data);
});

I had to:

Array.prototype.forEach.call(
   queue,
    ( element ) =>
    {
        (element)(data);
    }

); 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.