0

My directive has a custom event, say my-event used like:

<div (my-event)="handle($event)">

and user handles the event like:

async handle(e) {
  await handleEvent(e);
}

Then I like to perform a specific action after the event is handled by user-provided code like above.

Currently what I am doing is to provide a done function from the directive:

    // ...
    this.myEvent.emit({ event: e, done: this.done });
  }

  done = () => { /* do something */ };

And let user call done function once it finished handling the event:

async handle({ event, done }) {
  await handleEvent(event);
  done();
}

My question: Would it be possible to move calling-done-part from user code to the directive so that user just handles the event as required without worrying about calling done function?

bob
  • 2,674
  • 1
  • 29
  • 46
  • I actually like your approach, because otherwise it seems you'd have to use `ViewChild` in the parent component to gain access to the child component and call its `done` method explicitly. But this would just accomplish what you already have, with the additional drawback of coupling the parent to the child. – Frank Modica Aug 10 '18 at 23:35
  • Alternatively, maybe the parent can pass an observable to the child as an `@Input`, and the child can subscribe and call its own `done` method when the parent is finished with its async work. A similar idea would be an `@Input` boolean variable like `isDone` to which the child responds and sets back to false, but that's not very elegant. I'm curious to see better ideas from others! – Frank Modica Aug 10 '18 at 23:35
  • Since you're ok with the child knowing that the parent is doing async work, maybe instead of the child emitting an event via `@Output`, it could take in an async callback via `@Input` and `await` that function and then call its own `done` method. – Frank Modica Aug 10 '18 at 23:43
  • @FrankModica thanks for the comment. I didn't like the current way as user has to call `done` everywhere the directive is being used. I am feeling like `done` is the business belong to the directive and user (or parent as you call it) doesn't need to know its existence.. – bob Aug 11 '18 at 00:00

0 Answers0