diff --git a/lib/eventDispatcher.js b/lib/eventDispatcher.js index 53acb9aa..46ba435c 100644 --- a/lib/eventDispatcher.js +++ b/lib/eventDispatcher.js @@ -112,8 +112,13 @@ EventDispatcher.prototype = { } if (events) { + for (var i = 0, len = events.length; i < len; i++) { self.undispatchedEventsQueue.push(events[i]); + // If there are a lot of events then we can hit issues with the call stack size when processing in one go + if(i % 1000 === 0){ + trigger(self); + } } } diff --git a/test/eventDispatcherTest.js b/test/eventDispatcherTest.js index 9bba76bb..129da510 100644 --- a/test/eventDispatcherTest.js +++ b/test/eventDispatcherTest.js @@ -92,6 +92,46 @@ describe('EventDispatcher', function () { }); + it('should not crash when there are lots of pending events', function (done) { + + var eventsInStore = []; + + for(var i = 0; i < 10000; i++){ + eventsInStore.push({ + payload: { + index: i + } + }); + } + + function getUndispatchedEvents (callback) { + callback(null, eventsInStore); + } + + var publishedEvents = []; + + function publisher (evt) { + publishedEvents.push(evt); + check(); + } + + function check () { + if (publishedEvents.length === eventsInStore.length) { + done(); + } + } + + var eventDispatcher = new EventDispatcher(publisher, { + getUndispatchedEvents: getUndispatchedEvents, + setEventToDispatched: function (evt, callback) { callback(null); }}); + expect(eventDispatcher.undispatchedEventsQueue.length).to.eql(0); + + eventDispatcher.start(function(err) { + expect(err).not.to.be.ok(); + }); + + }); + }); describe('and calling addUndispatchedEvents', function () {