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

feat: Add a geoOnce function. #1097

Merged
merged 1 commit into from
Jun 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
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
22 changes: 22 additions & 0 deletions src/object.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,28 @@ var object = function () {
return m_this;
};

/**
* Bind an event handler to this object that will fire once and then
* deregister itself.
*
* @param {string} event An event from {@link geo.event} or a user-defined
* value.
* @param {function} handler A function that is called when `event` is
* triggered. The function is passed a {@link geo.event} object.
* @returns {function} The actual bound handler. This is a wrapper around
* the handler that was passed to the function.
*/
this.geoOnce = function (event, handler) {
let wrapper;

wrapper = function (args) {
m_this.geoOff(event, wrapper);
handler.call(m_this, args);
};
m_this.geoOn(event, wrapper);
return wrapper;
};

/**
* Report if an event handler is bound to this object.
*
Expand Down
29 changes: 29 additions & 0 deletions tests/cases/object.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,35 @@ describe('geo.object', function () {
expect(foo.ncalls).toBe(2);
});

it('Make a single object with a once event handler', function () {
var obj = new geo.object(),
evtData = {},
foo = new CallCounter(evtData);

expect(obj.geoIsOn('testevent')).toBe(false);
let handler = obj.geoOnce('testevent', foo.call);
expect(obj.geoIsOn('testevent')).toBe(true);
expect(obj.geoIsOn('testevent', foo.call)).toBe(false);
expect(obj.geoIsOn('testevent', handler)).toBe(true);
obj.geoTrigger('anotherevent', evtData);
expect(foo.ncalls).toBe(0);
expect(obj.geoIsOn('testevent', handler)).toBe(true);

obj.geoTrigger('testevent', evtData);
expect(foo.ncalls).toBe(1);
expect(obj.geoIsOn('testevent', handler)).toBe(false);

obj.geoTrigger('testevent', evtData);
expect(foo.ncalls).toBe(1);

obj.geoTrigger('test', evtData);
expect(foo.ncalls).toBe(1);

expect(obj.geoIsOn('testevent')).toBe(false);
obj.geoTrigger('testevent', evtData);
expect(foo.ncalls).toBe(1);
});

it('Make a single object with several handlers on one event', function () {
var obj = new geo.object(),
evtData = {},
Expand Down