Skip to content

Commit

Permalink
fix: onPopState listener removal
Browse files Browse the repository at this point in the history
  • Loading branch information
troch committed Jul 24, 2015
1 parent cd805ef commit 0d5fea1
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 15 deletions.
23 changes: 8 additions & 15 deletions modules/router5.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,18 +22,12 @@ class Router5 {
this.rootNode = routes instanceof RouteNode ? routes : new RouteNode('', '', routes)
this.options = {
useHash: false,
hashPrefix: ''
hashPrefix: '',
base: window.location.pathname.replace(/\/$/, '')
}
Object.keys(opts).forEach(opt => this.options[opt] = opts[opt])
this._setBase()
return this
}

/**
* @private
*/
_setBase() {
this.base = this.options.base || window.location.pathname.replace(/\/$/, '')
// Bind onPopState
this.boundOnPopState = this.onPopState.bind(this)
}

/**
Expand All @@ -44,7 +38,6 @@ class Router5 {
*/
setOption(opt, val) {
this.options[opt] = val
if (opt === 'base') this._setBase()
return this
}

Expand Down Expand Up @@ -109,7 +102,7 @@ class Router5 {
let startState = this.matchPath(startPath)

let cb = (err, state) => {
window.addEventListener('popstate', this.onPopState.bind(this))
window.addEventListener('popstate', this.boundOnPopState)
if (done) done(err, state)
}

Expand Down Expand Up @@ -144,7 +137,7 @@ class Router5 {
this.lastStateAttempt = null
this.started = false

window.removeEventListener('popstate', this.onPopState.bind(this))
window.removeEventListener('popstate', this.boundOnPopState)
return this
}

Expand Down Expand Up @@ -328,7 +321,7 @@ class Router5 {
getLocation() {
let path = this.options.useHash
? window.location.hash.replace(new RegExp('^#' + this.options.hashPrefix), '')
: window.location.pathname.replace(new RegExp('^' + this.base), '')
: window.location.pathname.replace(new RegExp('^' + this.options.base), '')
return path + window.location.search;
}

Expand All @@ -340,7 +333,7 @@ class Router5 {
* @return {String} The built URL
*/
buildUrl(route, params) {
return (this.options.useHash ? window.location.pathname + '#' + this.options.hashPrefix : this.base) +
return (this.options.useHash ? window.location.pathname + '#' + this.options.hashPrefix : this.options.base) +
this.rootNode.buildPath(route, params)
}

Expand Down
11 changes: 11 additions & 0 deletions modules/window.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
function getWindow() {
try {
return window
} catch(e) {
return null
}
}

let win = getWindow()

export default win

0 comments on commit 0d5fea1

Please sign in to comment.