elanh
elanh

Reputation: 1441

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.

Upvotes: 2

Views: 2004

Answers (3)

Pablo Cantero
Pablo Cantero

Reputation: 6357

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

Upvotes: 0

David Sulc
David Sulc

Reputation: 25994

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.

Upvotes: 1

sQVe
sQVe

Reputation: 2015

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.

Upvotes: 2

Related Questions