使用Sammy.js取消路线而不影响历史记录

Joh*_*apa 9 javascript url-routing sammy.js single-page-application toastr

我想拦截Sammy的所有路线变化,首先检查是否有待处理的动作.我使用sammy.beforeAPI 完成了这个,我返回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;
});
Run Code Online (Sandbox Code Playgroud)

Joh*_*apa 17

如果其他人遇到这个,这里是我结束的地方.我决定使用context.setLocationsammy 的功能来处理重置路线.

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;
});
Run Code Online (Sandbox Code Playgroud)