Permalink
Browse files

Adding `async` boolean option to `Publisher` constructor.

If present and truthy, all events will be published asynchronously. This behavior is not the default.
  • Loading branch information...
1 parent ecab43a commit 5d3a901857c3e178cc5ff586263647e4092596a9 @domenic committed Jan 26, 2012
Showing with 31 additions and 2 deletions.
  1. +9 −2 lib/pubit.js
  2. +22 −0 test/3 options.coffee
View
@@ -5,7 +5,6 @@
// * publisher.mixinEmitter(that)? publish = pubit.makeEmitter(that)?
// * restricted event names? would be a constructor parameter
// * more argument validation (or remove argument validation, not sure yet)
-// * think about the role of async (publisher? subscriber? always?)
var dict = require("dict");
var emitter = require("./emitter");
@@ -50,13 +49,21 @@ exports.Publisher = function (options) {
}
}
- function callListenersFor(eventName, args, listenersDict) {
+ function callListenersForSync(eventName, args, listenersDict) {
// .slice() is important to deal with self-unsubscribing listeners
listenersDict.get(eventName).slice().forEach(function (listener) {
callListener(listener, args);
});
}
+ function callListenersForAsync(eventName, args, listenersDict) {
+ process.nextTick(function () {
+ callListenersForSync(eventName, args, listenersDict);
+ });
+ }
+
+ var callListenersFor = options.async ? callListenersForAsync : callListenersForSync;
+
that.publish = function (eventName, args) {
if (typeof eventName !== "string") {
throw new TypeError("eventName argument must be a string.");
View
@@ -23,6 +23,28 @@ describe "Publisher options", ->
sinon.assert.calledWith(onListenerError, error)
+ describe "async", ->
+ beforeEach ->
+ publisher = new Publisher(async: true)
+ emitter = publisher.emitter
+
+ it "should result in events being published asynchronously", (next) ->
+ listener1 = sinon.spy()
+ listener2 = sinon.spy()
+ emitter.on("event1", listener1)
+ emitter.on("event2", listener2)
+
+ publisher.publish("event1")
+ publisher.publish("event2")
+
+ sinon.assert.notCalled(listener1)
+ sinon.assert.notCalled(listener2)
+
+ process.nextTick ->
+ sinon.assert.called(listener1)
+ sinon.assert.called(listener2)
+ next()
+
it "should be validated", ->
expect(-> new Publisher(null)).to.throw(TypeError)
expect(-> new Publisher(5)).to.throw(TypeError)

0 comments on commit 5d3a901

Please sign in to comment.