Hashbang URLs using Ember.js

痞子三分冷 提交于 2019-11-27 04:00:39
twiz

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'
})

Extending Ember.HashLocation would be the way to go.

For a clean implementation, you can do the following.

Ember.Location.registerImplementation('hashbang', Ember.HashLocation.extend({
  // overwrite what you need, for example:
  formatURL: function(url) {
    return '#!' + url;
  }
  // you'll also need to overwrite setURL, getURL, onUpdateURL...
})

Then instruct your App Router to use your custom implementation for location management:

App.Router.reopen({
  location: 'hashbang'
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!