Search code examples
backbone.js

Backbone.js loads URL twice because of encoding mismatch


I'm still using Backbone.js and am having some problems with URL's loading twice (at least in Chrome) when there is JSON in the hash.

Say I want to navigate to this hash: #{"name":"Viktor"}. After encoding it with encodeURIComponent('{"name":"Viktor"}') it becomes %7B%22name%22%3A%22Viktor%22%7D.

If I then try to navigate to the hash like this.navigate('%7B%22name%22%3A%22Viktor%22%7D') Backbone decodes the hash to #{"name":"Viktor"} and saves it. Then a hashchange event is triggered which calls Backbone.history.checkUrl() which indirectly calls Backbone.history.getHash() and returns hash #{%22name%22:%22Viktor%22} from window.location.href, but this is only partly decoded, at least in Chrome.

This leads to the following check failing:

if (current === this.fragment) return false;

Because #{"name":"Viktor"} does not equal #{%22name%22:%22Viktor%22}. I think this is the gist of the problem. If I override Backbone.history.getHash() and replace %22 with " my problem is solved, but I feel I should do something different?

Thank you in advance!


Solution

  • Your issue is a bug fixed in Backbone 1.4, so I will suggest updating your Backbone version.

    The only way I think it can be solved is patching Backbone as you done.