| @@ -1,33 +1,67 | |||||
| 1 | import { ICancellation } from "./interfaces"; |
|
1 | import { ICancellation } from "./interfaces"; | |
|
|
2 | import { argumentNotNull } from "./safe"; | |||
| 2 |
|
3 | |||
| 3 | export class Cancellation implements ICancellation { |
|
4 | export class Cancellation implements ICancellation { | |
|
|
5 | private _reason: any; | |||
|
|
6 | private _cbs: Array<(e) => void>; | |||
|
|
7 | ||||
|
|
8 | constructor(action: (cancel: (e) => void) => void) { | |||
|
|
9 | argumentNotNull(action, "action"); | |||
|
|
10 | ||||
|
|
11 | action(this._cancel.bind(this)); | |||
|
|
12 | } | |||
|
|
13 | ||||
| 4 | isSupported(): boolean { |
|
14 | isSupported(): boolean { | |
| 5 |
return |
|
15 | return true; | |
| 6 | } |
|
16 | } | |
| 7 | throwIfRequested(): void { |
|
17 | throwIfRequested(): void { | |
|
|
18 | if (this._reason) | |||
|
|
19 | throw this._reason; | |||
| 8 | } |
|
20 | } | |
| 9 |
|
21 | |||
| 10 | isRequested(): boolean { |
|
22 | isRequested(): boolean { | |
| 11 |
return |
|
23 | return !!this._reason; | |
| 12 | } |
|
24 | } | |
| 13 |
|
25 | |||
| 14 |
register( |
|
26 | register(cb: (e: any) => void): void { | |
| 15 |
|
27 | argumentNotNull(cb, "cb"); | ||
|
|
28 | ||||
|
|
29 | if (this._reason) { | |||
|
|
30 | cb(this._reason); | |||
|
|
31 | } else { | |||
|
|
32 | if (!this._cbs) | |||
|
|
33 | this._cbs = [cb]; | |||
|
|
34 | else | |||
|
|
35 | this._cbs.push(cb); | |||
|
|
36 | } | |||
| 16 | } |
|
37 | } | |
| 17 |
|
38 | |||
| 18 | static readonly none : Cancellation = { |
|
39 | private _cancel(reason) { | |
|
|
40 | if (this._reason) | |||
|
|
41 | return; | |||
|
|
42 | ||||
|
|
43 | this._reason = (reason = reason || new Error("Operation cancelled")); | |||
|
|
44 | ||||
|
|
45 | ||||
|
|
46 | if (this._cbs) { | |||
|
|
47 | this._cbs.forEach(cb => cb(reason)); | |||
|
|
48 | this._cbs = null; | |||
|
|
49 | } | |||
|
|
50 | } | |||
|
|
51 | ||||
|
|
52 | static readonly none: ICancellation = { | |||
| 19 | isSupported(): boolean { |
|
53 | isSupported(): boolean { | |
| 20 | return false; |
|
54 | return false; | |
| 21 | }, |
|
55 | }, | |
| 22 |
|
56 | |||
| 23 | throwIfRequested(): void { |
|
57 | throwIfRequested(): void { | |
| 24 | }, |
|
58 | }, | |
| 25 |
|
59 | |||
| 26 | isRequested(): boolean { |
|
60 | isRequested(): boolean { | |
| 27 | return false; |
|
61 | return false; | |
| 28 | }, |
|
62 | }, | |
| 29 |
|
63 | |||
| 30 | register(_cb: (e:any) => void): void { |
|
64 | register(_cb: (e: any) => void): void { | |
| 31 | } |
|
65 | } | |
| 32 | }; |
|
66 | }; | |
| 33 | } No newline at end of file |
|
67 | } | |
General Comments 0
You need to be logged in to leave comments.
Login now
