Skip to content

Commit

Permalink
Adds a subscribeAll() method to the client to handle any events
Browse files Browse the repository at this point in the history
Usage:

    client.subscribeAll(function(message) {
        console.log(message.action);
    });

Only accepts one handler and will overwrite any previously existing
handlers. Addresses #111
  • Loading branch information
AndrewRayCode committed Jun 28, 2016
1 parent 46cbc22 commit 09ba503
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
8 changes: 8 additions & 0 deletions client.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ function createReporter() {
var processUpdate = require('./process-update');

var customHandler;
var subscribeAllHandler;
function processMessage(obj) {
if (obj.action == "building") {
if (options.log) console.log("[HMR] bundle rebuilding");
Expand All @@ -144,10 +145,17 @@ function processMessage(obj) {
} else if (customHandler) {
customHandler(obj);
}

if (subscribeAllHandler) {
subscribeAllHandler(obj);
}
}

if (module) {
module.exports = {
subscribeAll: function subscribeAll(handler) {
subscribeAllHandler = handler;
},
subscribe: function subscribe(handler) {
customHandler = handler;
},
Expand Down
33 changes: 33 additions & 0 deletions test/client-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,36 @@ describe("client", function() {
}));
sinon.assert.calledOnce(processUpdate);
});
it("should call subscribeAll handler on default messages", function() {
var spy = sinon.spy();
client.subscribeAll(spy);
var message = {
action: 'built',
time: 100,
hash: 'deadbeeffeddad',
errors: [],
warnings: [],
modules: []
};

var eventSource = window.EventSource.lastCall.returnValue;
eventSource.onmessage(makeMessage(message));

sinon.assert.calledOnce(spy);
sinon.assert.calledWith(spy, message);
});
it("should call subscribeAll handler on custom messages", function() {
var spy = sinon.spy();
client.subscribeAll(spy);

var eventSource = window.EventSource.lastCall.returnValue;
eventSource.onmessage(makeMessage({
action: 'thingy'
}));

sinon.assert.calledOnce(spy);
sinon.assert.calledWith(spy, { action: 'thingy' });
});
it("should call only custom handler on custom messages", function() {
var spy = sinon.spy();
client.subscribe(spy);
Expand All @@ -47,6 +77,9 @@ describe("client", function() {
eventSource.onmessage(makeMessage({
custom: 'thingy'
}));
eventSource.onmessage(makeMessage({
action: 'built'
}));

sinon.assert.calledOnce(spy);
sinon.assert.calledWith(spy, { custom: 'thingy' });
Expand Down

0 comments on commit 09ba503

Please sign in to comment.