Search code examples
javascriptbackbone.jsurl-encoding

Prevent Backbone.history.navigate from decoding URL fragment


I'm triggering Backbone's navigate function to change the URL after an event fires.

Code

Backbone.history.navigate("?q=" + encodeURIComponent(searchQuery))

In my case, searchQuery could be something like max müller, thus containing spaces and unicode characters. That's why I have to encode it with encodeURIComponent into max+m%C3%BCller.

But within Backbones navigate function, my searchQuery is beeing decoded back to "max müller" and returned like that.

So at the end the URL gets changed into

myroot.com/?q=max müller

which is not a valid URL. Instead it should be like this:

myroot.com/?q=max+m%C3%BCller

As far as I can think, there are two possible ways to solve this:

 1. changing/extending Backbone.history.navigate to return the encoded
    fragment

 2. recreating Backbone's navigate functionality to change the URL with plain Javascript or using any other library

But why isn't it Backbone's default behaviour? It doesn't make sense to create an invalid URL.


Solution

  • You can see the answer to this while looking at the backbone js source code:

    https://github.com/jashkenas/backbone/blob/master/backbone.js#L1817

    Basically in order to match the url to your routes you need to decode the url. It kinda makes sense as you wouldn't want url encoded routes in your code - though that doesn't really help you sadly.

    I suspect extending would be the most sensible thing to do