Skip to content

Commit

Permalink
don't invoke action from subscribe call (#9)
Browse files Browse the repository at this point in the history
removing subscribe overloading (subscribe can no longer be used as an
action / event invocation)

closes #8
  • Loading branch information
morungos authored Sep 8, 2022
1 parent 1050829 commit 8c0b000
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 18 deletions.
15 changes: 4 additions & 11 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ export default function (state, states = {}) {
let proxy;

function subscribe(callback) {
if (typeof callback !== 'function') {
throw new TypeError("Invalid callback");
}
subscribers.add(callback);
callback(state);
return () => subscribers.delete(callback);
Expand Down Expand Up @@ -64,17 +67,7 @@ export default function (state, states = {}) {
* - subscribe() also behaves as an event invoker when called with any args other than a
* single callback (or when debounced)
*/
function subscribeOrInvoke(...args) {
if (args.length === 1 && args[0] instanceof Function) {
return subscribe(args[0]);
} else {
invoke('subscribe', ...args);
}
}

subscribeOrInvoke.debounce = debounce.bind(null, 'subscribe');

proxy = new Proxy({ subscribe: subscribeOrInvoke }, {
proxy = new Proxy({ subscribe }, {
get(target, property) {
if (!Reflect.has(target, property)) {
target[property] = invoke.bind(null, property);
Expand Down
16 changes: 9 additions & 7 deletions test/units.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,20 +61,22 @@ describe('a finite state machine', () => {
unsubscribe();
});

it('should call subscribe action handler when invoked with no args', () => {
machine.subscribe();
assert.calledOnce(states.off.subscribe);
it('should fail subscribe action handler when invoked with no args', () => {
assert.throws(() => {
machine.subscribe();
}, TypeError);
});

it('should call subscribe action handler when invoked with single non-function arg', () => {
machine.subscribe('not a function');
assert.calledWithExactly(states.off.subscribe, 'not a function');
assert.throws(() => {
machine.subscribe('not a function');
}, TypeError);
});

it('should call subscribe action handler when invoked with multiple args', () => {
it('should not call subscribe action handler when invoked with multiple args', () => {
const fn = sinon.fake();
machine.subscribe(fn, null);
assert.calledWithExactly(states.off.subscribe, fn, null);
assert.neverCalledWith(states.off.subscribe, fn, null);
});
});

Expand Down

0 comments on commit 8c0b000

Please sign in to comment.