Skip to content

Commit

Permalink
Merge pull request #760 from OpenGeoscience/missing-event-handler
Browse files Browse the repository at this point in the history
Add a warning if an event handler is missing.
  • Loading branch information
manthey authored Jan 19, 2018
2 parents 03955ba + 9c2e3b1 commit 3396704
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/object.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ var object = function () {
return new object();
}

var util = require('./util');

var m_this = this,
m_eventHandlers = {},
m_idleHandlers = [],
Expand Down Expand Up @@ -75,6 +77,10 @@ var object = function () {
});
return m_this;
}
if (!util.isFunction(handler)) {
console.warn('Handler for ' + event + ' is not a function', handler, m_this);
return m_this;
}
if (!m_eventHandlers.hasOwnProperty(event)) {
m_eventHandlers[event] = [];
}
Expand Down Expand Up @@ -107,7 +113,11 @@ var object = function () {

if (m_eventHandlers.hasOwnProperty(event)) {
m_eventHandlers[event].forEach(function (handler) {
handler.call(m_this, args);
try {
handler.call(m_this, args);
} catch (err) {
console.warn('Event handler for ' + event + ' threw an error', err);
}
});
}

Expand Down
27 changes: 27 additions & 0 deletions tests/cases/object.js
Original file line number Diff line number Diff line change
Expand Up @@ -199,6 +199,33 @@ describe('geo.object', function () {
expect(foo.ncalls).toBe(3);
});

it('Test a non-function handler', function () {
sinon.stub(console, 'warn', function () {});
var obj = new geo.object(),
evtData = {},
handler = new CallCounter(evtData);

obj.geoOn('event1', undefined);
expect(console.warn.calledOnce);
obj.geoOn('event1', handler.call);
obj.geoTrigger('event1', evtData);
expect(handler.ncalls).toBe(1);
console.warn.restore();
});

it('Test a handler that has an error', function () {
sinon.stub(console, 'warn', function () {});
var obj = new geo.object(),
evtData = {},
handler = new CallCounter(evtData);

obj.geoOn('event1', function () { throw new Error('fail'); });
obj.geoOn('event1', handler.call);
obj.geoTrigger('event1', evtData);
expect(handler.ncalls).toBe(1);
expect(console.warn.calledOnce);
console.warn.restore();
});
});

});

0 comments on commit 3396704

Please sign in to comment.