Backbonejs - Trigger a route event without changing the URL

In Backbone, is there any way to trigger a route event handler, without changing the URL?

What I mean is that I want to trigger a route handler, but I don't want to change the URL. Hence, I don't want to use

router.navigate(route, {trigger: true});

as this will cause the URL to change.

Answers


The router itself is connected to a function. The simple answer is to call the function straight away, simply bypassing the route handling.

Example
(function( $, Backbone ) {
    var exports = window.app = window.app || {},
        Router = Backbone.Router.extend({
            // Here you declare what the routes are in your router
            // and what functionality they should trigger.
            routes: {
                "help"                : "help",
                "search/:query"       : "search",
                "search/:query/p:page": "search"
            },

            // Declare route functions.
            help  : function() {},
            search: function( query, page ) {}
        });

    // Export the router.
    exports.router = new Router();

    // Just a dummy object for calling the router.
    var cookieMonster = {
        init: function() {
            // Do something on init.

            // End with calling the route help function.
            exports.router.help();
        }
    };
}(jQuery, Backbone));

cookieMonster.init() would in this case end with a call to the help function in the router.

A tip is to look at Backbone Marionette where you have a Controller which has the function logic seperated from the routes, one of many things that make Marionette awesome.


For what its worth, Marionette routing is explained extensively here: http://samples.leanpub.com/marionette-gentle-introduction-sample.pdf

The strategy that is discussed is separating URL management from application reactions (e.g. switching sub-applications). This means that you're then free to have your app trigger a handler (using a Marionette event) without modifying the URl fragment.


Have you tried Backbone.history.loadUrl(route);?


Need Your Help

How to know when a dynamically loaded CSS file is fully loaded and active?

javascript css lazy-loading

I have used a technique described in a post on StackOverflow to dynamically add a CSS file to the HEAD tag of an HTML page (in JavaScript). The method to check whether the CSS file has been fully l...

How to change facet labels in ggplot2?

r ggplot2

I am trying to change the facet labels in ggplot2. I found this solution