Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone Router - Browser Back Button Not Triggering Router Methods

Tags:

backbone.js

I have a Backbone Router set up that seemingly works - the routes get triggered properly, the views update, etc. However, when I press the browser's "Back" button, the routes aren't triggered at all. Also, typing in a URL into the browser doesn't trigger the routers either. Is there some step I'm missing to bind the browser specific things to Backbone (Firefox 11).

Setup

var messageRouter = new MessageRouter({view: messageListView});
Backbone.history.start();

Trigger

Backbone.history.navigate("#/view/" + $(this).data("filter-type"), {trigger: true});

Router Code

var MessageRouter = Backbone.Router.extend({

    view : null, /* should always be overridden */

    initialize : function(options)
    {
        this.view = options.view;
    },

    routes : {
        "" : "default",
        "/view/:filter" : "filter",
        "camera" : "camera"
    },

    default : function() {
    },

    filter : function(filterString) {
        this.view.setFilter(filterString);
        this.view.rerender();
    },

    camera : function(cameraString) {
    }

});
like image 914
bluedevil2k Avatar asked Apr 30 '12 16:04

bluedevil2k


2 Answers

You should call router.navigate using the same path that you had already defined. ie:

trigger

messageRouter.navigate("/view/" + $(this).data("filter-type"), {trigger: true});

router

 routes : {
        "" : "default",
        "/view/:filter" : "filter",
        "camera" : "camera"
    },
like image 115
Martin Borthiry Avatar answered Oct 17 '22 02:10

Martin Borthiry


It might be the word default that's messing it up as it's a reserved word.

Either put quotes around the key 'default' in MessageRouter, or call it something else, like 'defaultRoute'.

'default': function() {},
defaultRoute: function() {}

http://jsfiddle.net/uwjDq/2/ -Seems to work OK here, including using the back button.

like image 1
Toddish Avatar answered Oct 17 '22 01:10

Toddish