Hashbang URLs using Ember.js

前端 未结 2 1035
再見小時候
再見小時候 2020-11-30 04:11

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

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

App.Router.map         


        
相关标签:
2条回答
  • 2020-11-30 04:49

    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'
    })
    
    0 讨论(0)
  • 2020-11-30 04:50

    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'
    })
    
    0 讨论(0)
提交回复
热议问题