Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

第一次跳转,bind事件执行2次 #28

Open
JaneScript opened this issue Aug 27, 2016 · 4 comments
Open

第一次跳转,bind事件执行2次 #28

JaneScript opened this issue Aug 27, 2016 · 4 comments

Comments

@JaneScript
Copy link

第一次跳转或者手动输入Url,bind的方法会执行2次,直接刷新则不会出现这个问题

@EastWoodYang
Copy link

我也遇到了...

@cgfeel
Copy link

cgfeel commented Aug 28, 2016

我也遇到了。。。

@rming
Copy link

rming commented Aug 31, 2016

同样的问题

@woshiguabi
Copy link

解决了这个问题。
当直接访问的时候地址后面不带hash,进行init,先添加了hashchange事件后,进行默认路由的跳转

 const hash = util.getHash(location.href);
 const route = util.getRoute(this._routes, hash);
 this.go(route ? hash : this._default);

此时hash为空,getHash返回的是 /

function getHash(url) {
     return url.indexOf('#') !== -1 ? url.substring(url.indexOf('#') + 1) : '/';
}

然后会go到默认路由(一般是/)。
但此时实际hash为空,在go中的enter又有一句
location.hash =#${url};
导致hash从空变成#/,此处触发了一次hashchange事件,所以会重复触发一次bind。

一个不太优雅的解决方案
首先将getHash中的空hash返回'/'改为返回空

function getHash(url) {
     return url.indexOf('#') !== -1 ? url.substring(url.indexOf('#') + 1) : '';
}

然后将init中的默认路由跳转添加一次判断,然后使用location.hash去触发hashchange事件

const hash = util.getHash(location.href);
if(!hash){
    location.hash = '#' + this._default;
} else {
    const route = util.getRoute(this._routes, hash);
    this.go(route ? hash : this._default);
}
return this;

@progrape 希望jf大大看看这样解决有没有什么问题

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants