1

我已经为我正在处理的站点构建了一个原始路由功能。
这个想法是检查传入的 URL,然后将浏览器发送到站点的适当部分。

我注意到,如果传入的 URL 与它应该推送到的 URL 相同,则 pushState 不会触发。意思是,如果我去,domain.com/journal它不会开火。该 URL 与路由器应该推送到的 URL 相同:) History.pushState({ id: 'journal' }, site.title+' — '+'Journal', site.url+'/journal' );

但如果我domain.com/journal/改为,它会火。这是为什么?


简化的路由代码

setTimeout(function() {
      uri = window.location.pathname.replace(/^\/([^\/]*).*$/, '$1');
      if(uri === 'journal') {
        uri = window.location.pathname.split( '/' );
        if(uri[2]) {
          History.pushState({ id: 'post', no: uri[2] }, site.title+' — '+'Journal', site.url+'/journal/'+uri[2] );
        } else {
          History.pushState({ id: 'journal' }, site.title+' — '+'Journal', site.url+'/journal' );
        }
      } else if(uri === 'contact') {
        History.pushState({ id: 'contact' }, site.title+' — '+'Contact', site.url+'/contact' );
      } else {
        History.pushState({ id: 'gallery' }, site.title, site.url );
      }
}, 1);

History.Adapter.bind(window,'statechange',function(){ // Note: We are using statechange instead of popstate
    var State = History.getState(); // Note: We are using History.getState() instead of event.state  
    Roots.common.history(State);
}

history: function(State) {
    navigate(State.data.id, State.data.no);
},

navigate: function(section, no) {
  if(section === 'gallery') {
    // do gallery stuff
  } else if(section === 'journal') {
    // do journal stuff
  } else if(section === 'contact') {
    // do contact stuff
  } else if(section === 'post') {
    // do post stuff
  }
}
4

1 回答 1

1

无论如何让它触发的简单解决方案是将随机数据与 pushState 一起发送

History.pushState({ id: 'gallery', randomData: window.Math.random() }, site.title, site.url );
于 2014-06-08T23:20:09.003 回答