Backbone default route using route property

I'm working with a Backbone project, and in our router, we specify the default route at the end of the property routes

:

routes: {
    "things": "stuff",
    "*actions": "default"
}

      

With a bit of searching, I saw a couple of places like this StackOverflow question and the Backbone Tutorial , which suggests adding a default route this way.

However, this worries me a lot because from what I see in the Backbone source the property is routes

just iterating over to add all the routes in it, and as far as I know, iterating over an object in JavaScript does not guarantee any ordering. Therefore, with the above definition routes

, it does not guarantee that the default route has the lowest priority just because it is at the end of the definition.

Is the behavior essentially undefined here and everything is really working out just a matter of pure luck, or is there something else going on that actually makes this safe for you?

+3


source to share


1 answer


As you have determined, routes derived from a property route

are not in guaranteed order ... although in practice many browsers will traverse them in a specific order, and you can also guarantee ordering using the route method.

But what about the two examples you gave? Well, if you take a close look at them, you will notice that they have no other routes on the same level as you. The splat syntax exists simply to provide a more readable way of writing "nothing that is not a question mark" (ie ([^?]*?)

); it is not actually intended to be processed by default.

So if you are trying to achieve:

if (url == 'things') {
    doStuff();
} else {
    doActions();
}

      



you have two options. If you want to change the structure of the url, you can simply:

/things
/actions/*actions

      

If it doesn't, you just need to define a route that is different:

routes: {':rootLevelPath': rootLevelPathRoute},
rootLevelPathRoute: function(rootLevelPath) {
    if (rootLevelPath == 'things') {
        doThings();
    } else {
        doActions();
    }
}

      

+1


source







All Articles