Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a warning if an event handler is missing. #760

Merged
merged 2 commits into from
Jan 19, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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();
});
});

});