Skip to content

Commit

Permalink
Merge pull request #23 from jaredwray/adding-in-onceHook
Browse files Browse the repository at this point in the history
adding in onceHook
  • Loading branch information
jaredwray authored Oct 29, 2024
2 parents fb85689 + 407c013 commit c9f3838
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
32 changes: 32 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,38 @@ myClass.onHook('before:myMethod2', async (data) => {
});
```

## .onceHook(eventName, handler)

Subscribe to a hook event once.

```javascript
import { Hookified } from 'hookified';

class MyClass extends Hookified {
constructor() {
super();
}

async myMethodWithHooks() Promise<any> {
let data = { some: 'data' };
// do something
await this.hook('before:myMethod2', data);

return data;
}
}

const myClass = new MyClass();

myClass.onHookOnce('before:myMethod2', async (data) => {
data.some = 'new data';
});

myClass.myMethodWithHooks();

console.log(myClass.hooks.length); // 0
```

## .removeHook(eventName)

Unsubscribe from a hook event.
Expand Down
15 changes: 15 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,21 @@ export class Hookified extends Eventified {
}
}

/**
* Adds a handler that only executes once for a specific event
* @param event
* @param handler
*/
onceHook(event: string, handler: Hook) {
const hook = async (...arguments_: any[]) => {
this.removeHook(event, hook);
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
return handler(...arguments_);
};

this.onHook(event, hook);
}

/**
* Removes a handler function for a specific event
* @param {string} event
Expand Down
10 changes: 10 additions & 0 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,16 @@ describe('Hookified', () => {
expect(hookified.hooks.size).toBe(2);
});

test('onHookOnce will remove hook after execution', async () => {
const hookified = new Hookified();
// eslint-disable-next-line @typescript-eslint/no-empty-function
const handler = () => {};
hookified.onceHook('event', handler);
expect(hookified.getHooks('event')?.length).toEqual(1);
await hookified.hook('event');
expect(hookified.getHooks('event')?.length).toEqual(0);
});

test('onHook with Clear', async () => {
const hookified = new Hookified();
// eslint-disable-next-line @typescript-eslint/no-empty-function
Expand Down

0 comments on commit c9f3838

Please sign in to comment.