onlineracoon
onlineracoon

Reputation: 2970

Backbone router on every route

My problem is:

All the HTML is in a <div id="application"> container, which by default has 0 opacity. This is because JavaScript does some DOM positioning, so when this is all done I just add a class="rendered" into the <div id="application>" and then the page appears.

So the thing is, for every route in my Backbone router, I need something that is always triggered before the actual routing, or on each route, is this possible?

Thanks for help!

Upvotes: 2

Views: 1863

Answers (2)

Wyatt Anderson
Wyatt Anderson

Reputation: 9893

Backbone.Router emits events when a route triggers, so you can either bind to specific events or to all to capture all valid route changes. The event argument will contain the route callback name:

var MyRouter = Backbone.Router.extend({
    routes: {
        "foo": "bar"
    },

    initialize: function() {
        this.on('all', function(routeEvent) {
            // If you had clicked #foo, routeEvent would contain
            // `route:bar`. You can trigger your CSS changes here.
        });
    }
});

I feel like this sort of code would be better off in a view, but this ought to do what you ask for.

Upvotes: 10

Jordan Denison
Jordan Denison

Reputation: 2727

You could define one method in your router that takes a parameter. Then for every route, call that method and pass in one argument that will be used to determine which view to render. At the beginning of the method you could define whatever "on-every-router-call" logic you want to happen.

For example:

routes:
    "": "renderPage"
    ":page": "renderPage"


renderPage: (page) ->
// check if page is defined, if not render index, if it is, render that page

Upvotes: 2

Related Questions