[英]Cancel route using Sammy.js without affecting history
我想攔截Sammy的所有路線變化,首先檢查是否有待處理的動作。 我使用sammy.before
API完成了這個,我返回false來取消路由。 這使用戶保持在“頁面”上,但它仍然會更改瀏覽器地址欄中的哈希值,並將路徑添加到瀏覽器的歷史記錄中。 如果我取消路線,我不想在地址欄或歷史記錄中,但我希望地址保持不變。
目前,要解決此問題,我可以調用window.history.back(yuk)返回歷史記錄中的原始位置或sammy.redirect。 兩者都不太理想。
有沒有辦法讓sammy真正取消路由,使其保持在當前路由/頁面上,保留地址欄,並且不添加到歷史記錄中?
如果沒有,是否有另一個路由庫將執行此操作?
sammy.before(/.*/, function () {
// Can cancel the route if this returns false
var response = routeMediator.canLeave();
if (!isRedirecting && !response.val) {
isRedirecting = true;
// Keep hash url the same in address bar
window.history.back();
//this.redirect('#/SpecificPreviousPage');
}
else {
isRedirecting = false;
}
return response.val;
});
如果其他人遇到這個,這里是我結束的地方。 我決定使用sammy的context.setLocation
功能來處理重置路由。
sammy.before(/.*/, function () {
// Can cancel the route if this returns false
var
context = this,
response = routeMediator.canLeave();
if (!isRedirecting && !response.val) {
isRedirecting = true;
toastr.warning(response.message); // toastr displays the message
// Keep hash url the same in address bar
context.app.setLocation(currentHash);
}
else {
isRedirecting = false;
currentHash = context.app.getLocation();
}
return response.val;
});
使用問題和答案中提供的代碼時,您必須注意到您取消的路線也將在以后的所有呼叫中被阻止,因此不會再次評估routeMediator.canLeave。 兩次調用路由並根據當前狀態取消它是不可能的。
我可以產生與John Papa在SPA / Knockout課程中使用SammyJS時所做的相同的結果。
我使用Crossroads JS作為路由器,它依賴於Hasher JS來監聽瀏覽器“發出”的URL更改。
代碼示例是:
hasher.changed.add(function(hash, oldHash) {
if (pageViewModel.isDirty()){
console.log('trying to leave from ' + oldHash + ' to ' + hash);
hasher.changed.active = false;
hasher.setHash(oldHash);
hasher.changed.active = true;
alert('cannot leave. dirty.');
}
else {
crossroads.parse(hash);
console.log('hash changed from ' + oldHash + ' to ' + hash);
}
});
在重新審視一個較舊的項目並遇到類似情況后,我想分享另一種方法,以防其他人被引導到這里。
所需要的基本上是用於截取頁面和基於憑證重定向的現代“auth guard”模式。
運行良好的是使用Sammy.around(callback)
如下所示: Sammy.js docs:Sammy.Application around(callback)
然后,只需執行以下操作......
(function ($) {
var app = Sammy("body");
app.around(checkLoggedIn);
function canAccess(hash) {
/* access logic goes here */
return true;
}
// Authentication Guard
function authGuard(callback) {
var context = this;
var currentHash = app.getLocation();
if (!canAccess(currentHash)) {
// redirect
context.redirect("#/login");
}
else {
// execute the route path
callback();
}
};
})(jQuery);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.