简体   繁体   English

为什么我必须按两次返回才能回到Backbone?

[英]Why do I have to press back twice to go back in Backbone?

Live Demo of the problem 问题的现场演示

I have this little example app, where I try to implement a routing system with history. 我有这个小示例应用程序,在这里我尝试实现具有历史记录的路由系统。 It works as excepted, but for some reason I have to press the back button twice. 它的工作原理与众不同,但由于某种原因,我必须按两次后退按钮。 If you open the console, you can see the logs. 如果打开控制台,则可以看到日志。 When I press for example page1 and page2 and then the back link too, it logs page2 twice. 例如,当我按page1和page2,然后按反向链接时,它两次记录page2 Why? 为什么? If I press it again it logs page1 twice. 如果我再次按它,​​它将记录两次page1 What? 什么? Then it finally goes back. 然后终于回头了。 Why do I have to press it twice? 为什么我必须按两次? Why the logs are so crazy? 为什么日志如此疯狂? How can I make it work? 我该如何运作?

HTML 的HTML

<div id="home">Home</div>
<div id="page1">Page1</div>
<div id="page2">Page2</div>
<div id="back">Back</div>

JavaScript 的JavaScript

var app = {};
app.router = Backbone.Router.extend({

    routes: {
        '': 'home',
        'page1': 'page1',
        'page2': 'page2',
    },

    home: function () {
        console.log('home');
        Backbone.history.history.pushState('search');
        console.log(Backbone.history.history);
    },

    page1: function () {
        console.log('page1');
        Backbone.history.history.pushState('page1');
        console.log(Backbone.history.history);
    },

    page2: function () {
        console.log('page2');
        Backbone.history.history.pushState('page2');
        console.log(Backbone.history.history);
    },

});

var router = new app.router();
Backbone.history.start();

$(document).on('click', '#back', function () {
    console.log('back');
    console.log(Backbone.history.history);
    Backbone.history.history.back();
    console.log(Backbone.history.history);
    router.navigate(Backbone.history.history.state, {trigger: true, replace: true});
});

$(document).on('click', '#home', function () {
    router.navigate('home', {trigger: true, replace: true});
});

$(document).on('click', '#page1', function () {
    router.navigate('page1', {trigger: true, replace: true});
});

$(document).on('click', '#page2', function () {
    router.navigate('page2', {trigger: true, replace: true});
});

Does this serve your purpose : 这是否符合您的目的:

$(document).on('click', '#back', function () {
    window.history.back();
});

MDN window.history MDN window.history

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM