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

1.4k views Asked by At

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. Why? If I press it again it logs page1 twice. 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

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

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});
});
1

There are 1 answers

1
Niranjan Borawake On

Does this serve your purpose :

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

MDN window.history