|
3 | 3 | import type ActionCableConsumerService from 'codecrafters-frontend/services/action-cable-consumer'; |
4 | 4 | import type Store from '@ember-data/store'; |
5 | 5 | import Logstream from 'codecrafters-frontend/utils/logstream'; |
6 | | -import Modifier from 'ember-modifier'; |
| 6 | +import Modifier, { type ArgsFor } from 'ember-modifier'; |
7 | 7 | import { inject as service } from '@ember/service'; |
8 | 8 | import { registerDestructor } from '@ember/destroyable'; |
9 | 9 | import { action } from '@ember/object'; |
| 10 | +import type { Owner } from '@ember/test-helpers/build-owner'; |
10 | 11 |
|
11 | 12 | interface Signature { |
12 | 13 | Args: { |
13 | 14 | Positional: [(logstream: Logstream) => void, string]; |
14 | 15 | }; |
15 | 16 | } |
16 | 17 |
|
| 18 | +function cleanup(instance: LogstreamDidUpdateModifier) { |
| 19 | + if (instance.logstream) { |
| 20 | + instance.logstream.unsubscribe(); |
| 21 | + } |
| 22 | +} |
| 23 | + |
17 | 24 | export default class LogstreamDidUpdateModifier extends Modifier<Signature> { |
18 | 25 | @service declare actionCableConsumer: ActionCableConsumerService; |
19 | 26 | @service declare store: Store; |
20 | 27 |
|
21 | | - callback?: (logstream: Logstream) => void; |
22 | 28 | logstream?: Logstream; |
23 | 29 |
|
24 | | - @action |
25 | | - handleLogstreamDidPoll(): void { |
26 | | - this.callback!(this.logstream!); |
| 30 | + constructor(owner: unknown, args: ArgsFor<Signature>) { |
| 31 | + super(owner as Owner, args); |
| 32 | + registerDestructor(this, cleanup); |
27 | 33 | } |
28 | 34 |
|
29 | 35 | modify(_element: HTMLElement, [callback, logstreamId]: Signature['Args']['Positional']) { |
30 | | - this.logstream = new Logstream(logstreamId, this.actionCableConsumer, this.store, this.handleLogstreamDidPoll); |
31 | | - this.callback = callback; |
| 36 | + cleanup(this); |
32 | 37 |
|
33 | | - console.log(`subscribing to logstream#${logstreamId}`); |
| 38 | + this.logstream = new Logstream(logstreamId, this.actionCableConsumer, this.store, () => callback(this.logstream!)); |
34 | 39 | this.logstream.subscribe(); |
35 | | - |
36 | | - registerDestructor(this, () => { |
37 | | - console.log(`unsubscribing from logstream#${logstreamId}`); |
38 | | - this.logstream?.unsubscribe(); |
39 | | - }); |
40 | 40 | } |
41 | 41 | } |
42 | 42 |
|
|
0 commit comments