UNPKG

1.38 kBJavaScriptView Raw
1/**
2 * @class ApHistorys
3 */
4'use strict'
5
6/** @lends ApHistory */
7class ApHistory {
8 constructor (conf) {
9 const s = this
10 Object.assign(s, conf || {})
11 }
12
13 /**
14 * Push a history.
15 * @param {string} url - History url
16 */
17 push (url) {
18 const s = this
19 let history = s._getHistory()
20 if (!history) {
21 ApHistory.warn('`history` not found.')
22 return
23 }
24 history.pushState(null, '', url)
25 }
26
27 /**
28 * Register pop handler.
29 * @param {function} handler
30 */
31 onPop (handler) {
32 const s = this
33 let window = s._getWindow()
34 if (!window) {
35 ApHistory.warn('`window` not found.')
36 return
37 }
38 window.addEventListener('popstate', handler)
39 }
40
41 /**
42 * Deregister pop handler.
43 * @param {function} handler
44 */
45 offPop (handler) {
46 const s = this
47 let window = s._getWindow()
48 if (!window) {
49 ApHistory.warn('`window` not found.')
50 return
51 }
52 window.removeEventListener('popstate', handler)
53 }
54
55 _getWindow () {
56 const s = this
57 return typeof window === 'undefined' ? null : window
58 }
59
60 _getHistory () {
61 const s = this
62 return typeof history === 'undefined' ? null : history
63 }
64}
65
66Object.assign(ApHistory, {
67 /**
68 * Print warning.
69 * @param {string} msg - Warning message.
70 */
71 warn (msg) {
72 console.log('[ApHistory]', msg)
73 }
74})
75
76module.exports = ApHistory