Search code examples
ember.jsember-routerhashbang

Hashbang URLs using Ember.js


I am trying to set up my Router to use "hashbang" URLs (#!).

I tried this, but obviously it doesn't work:

App.Router.map(function() {
    this.route("index", { path: "!/" });
    this.route("otherState", { path: "!/otherState" });
});

Is this possible to do in Ember?


Solution

  • Teddy Zeenny's answer is mostly correct, and registerImplementation seems to be a clean way to implement this. I tried to just edit his answer to make it fully answer the question, but my edit got rejected.

    Anyway here is the full code to make Ember use hashbang URLs:

    (function() {
    
    var get = Ember.get, set = Ember.set;
    
    Ember.Location.registerImplementation('hashbang', Ember.HashLocation.extend({ 
    
        getURL: function() {
            return get(this, 'location').hash.substr(2);
        },
    
        setURL: function(path) {
            get(this, 'location').hash = "!"+path;
            set(this, 'lastSetURL', "!"+path);
        },
    
        onUpdateURL: function(callback) {
            var self = this;
            var guid = Ember.guidFor(this);
    
            Ember.$(window).bind('hashchange.ember-location-'+guid, function() {
                    Ember.run(function() {
                        var path = location.hash.substr(2);
                        if (get(self, 'lastSetURL') === path) { return; }
    
                        set(self, 'lastSetURL', null);
    
                        callback(location.hash.substr(2));
                    });
            });
        },
    
        formatURL: function(url) {
            return '#!'+url;
        }
    
    }));
    
    })();
    

    Then once you create your app you need to change the router to utilize the "hashbang" location implementation:

    App.Router.reopen({
        location: 'hashbang'
    })