기록을 업데이트하면서 페이지를 탐색하기 위해 history pushState및 replaceState메소드 를 사용하는 웹 앱을 만들었습니다 .
스크립트 자체는 거의 완벽하게 작동합니다. 페이지를 올바르게로드하고 던져야 할 때 페이지 오류를 발생시킵니다. 그러나 pushState여러 중복 항목을 기록하고 이전 항목을 교체 하는 이상한 문제가 기록에 있습니다.
예를 들어 다음을 순서대로 수행한다고 가정 해 보겠습니다.
index.php를 불러 오십시오 (이력 : Index)
profile.php로 이동합니다 (이력 : Profile, Index).
search.php로 이동합니다 (기록은 검색, 검색, 색인입니다).
dashboard.php로 이동
그런 다음 마지막으로 내 역사에서 가장 최근에 나온 것입니다.
대시
보드
대시 보드 대시 보드
검색
색인
이것의 문제점은 사용자가 앞으로 또는 뒤로 단추를 클릭 할 때 잘못된 페이지로 리디렉션되거나 다시 한 번 돌아가려면 여러 번 클릭해야한다는 것입니다. 그들이 가서 역사를 확인하면 말이되지 않습니다.
이것이 내가 지금까지 가진 것입니다.
var Traveller = function(){
this._initialised = false;
this._pageData = null;
this._pageRequest = null;
this._history = [];
this._currentPath = null;
this.abort = function(){
if(this._pageRequest){
this._pageRequest.abort();
}
};
// initialise traveller (call replaceState on load instead of pushState)
return this.init();
};
/*1*/Traveller.prototype.init = function(){
// get full pathname and request the relevant page to load up
this._initialLoadPath = (window.location.pathname + window.location.search);
this.send(this._initialLoadPath);
};
/*2*/Traveller.prototype.send = function(path){
this._currentPath = path.replace(/^\/+|\/+$/g, "");
// abort any running requests to prevent multiple
// pages from being loaded into the DOM
this.abort();
return this._pageRequest = _ajax({
url: path,
dataType: "json",
success: function(response){
// render the page to the dom using the json data returned
// (this part has been skipped in the render method as it
// doesn't involve manipulating the history object at all
window.Traveller.render(response);
}
});
};
/*3*/Traveller.prototype.render = function(data){
this._pageData = data;
this.updateHistory();
};
/*4*/Traveller.prototype.updateHistory = function(){
/* example _pageData would be:
{
"page": {
"title": "This is a title",
"styles": [ "stylea.css", "styleb.css" ],
"scripts": [ "scripta.js", "scriptb.js" ]
}
}
*/
var state = this._pageData;
if(!this._initialised){
window.history.replaceState(state, state.title, "/" + this._currentPath);
this._initialised = true;
} else {
window.history.pushState(state, state.title, "/" + this._currentPath);
}
document.title = state.title;
};
Traveller.prototype.redirect = function(href){
this.send(href);
};
// initialise traveller
window.Traveller = new Traveller();
document.addEventListener("click", function(event){
if(event.target.tagName === "a"){
var link = event.target;
if(link.target !== "_blank" && link.href !== "#"){
event.preventDefault();
// example link would be /profile.php
window.Traveller.redirect(link.href);
}
}
});
모든 도움을 주셔서 감사
합니다.
updateHistory함수 에 브라우저 기록을 추가하고 있음을 알았습니다 . 이제 updateHistoryTraveler ( window.Traveller = new Traveller();, constructor-> init-> send-> render-> updateHistory)를 초기화 할 때 eventListener redirect에서 두 번 호출 될 수 있습니다 click. 나는 그것을 시험하지 않았고, 단지 거친 추측이기 때문에 답이 아닌 주석으로 추가했습니다.