1
1
import { fireNavigateEvent } from './events'
2
2
import { History } from './history'
3
3
import { Scroll } from './scroll'
4
- import { Component , Page , PageHandler , PageResolver , PreserveStateOption , RouterInitParams } from './types'
4
+ import { Component , Page , PageEvent , PageHandler , PageResolver , PreserveStateOption , RouterInitParams } from './types'
5
5
import { hrefToUrl , isSameUrlWithoutHash } from './url'
6
6
7
7
class CurrentPage {
@@ -10,6 +10,11 @@ class CurrentPage {
10
10
protected resolveComponent ! : PageResolver
11
11
protected componentId = { }
12
12
protected onNewComponentCallbacks : VoidFunction [ ] = [ ]
13
+ protected onFirstLoadCallbacks : VoidFunction [ ] = [ ]
14
+ protected listeners : {
15
+ event : PageEvent
16
+ callback : VoidFunction
17
+ } [ ] = [ ]
13
18
protected firstPageLoad = true
14
19
15
20
public init ( { initialPage, swapComponent, resolveComponent } : RouterInitParams ) {
@@ -47,12 +52,18 @@ class CurrentPage {
47
52
replace = replace || isSameUrlWithoutHash ( hrefToUrl ( page . url ) , window . location )
48
53
replace ? History . replaceState ( page ) : History . pushState ( page )
49
54
50
- const isNewComponent = ! this . isTheSame ( page ) || this . firstPageLoad
55
+ const isNewComponent = ! this . isTheSame ( page )
51
56
52
57
this . page = page
53
58
54
59
if ( isNewComponent ) {
55
- this . onNewComponentCallbacks . forEach ( ( cb ) => cb ( ) )
60
+ this . listeners
61
+ . filter ( ( listener ) => listener . event === 'newComponent' )
62
+ . forEach ( ( listener ) => listener . callback ( ) )
63
+ }
64
+
65
+ if ( this . firstPageLoad ) {
66
+ this . listeners . filter ( ( listener ) => listener . event === 'firstLoad' ) . forEach ( ( listener ) => listener . callback ( ) )
56
67
}
57
68
58
69
this . firstPageLoad = false
@@ -105,11 +116,11 @@ class CurrentPage {
105
116
return this . page . component === page . component
106
117
}
107
118
108
- public onNewComponent ( cb : VoidFunction ) : VoidFunction {
109
- this . onNewComponentCallbacks . push ( cb )
119
+ public on ( event : PageEvent , callback : VoidFunction ) : VoidFunction {
120
+ this . listeners . push ( { event , callback } )
110
121
111
122
return ( ) => {
112
- this . onNewComponentCallbacks = this . onNewComponentCallbacks . filter ( ( callback ) => callback !== cb )
123
+ this . listeners = this . listeners . filter ( ( listener ) => listener . event !== event && listener . callback !== callback )
113
124
}
114
125
}
115
126
}
0 commit comments