使用Ember.js的Hashbang URL

twi*_*wiz 15 hashbang ember.js ember-router

我正在尝试设置我Router使用"hashbang"URL(#!).

我尝试过这个,但显然它不起作用:

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

这可以在Ember做吗?

twi*_*wiz 19

Teddy Zeenny的回答大多是正确的,registerImplementation似乎是一种干净的方式来实现这一点.我试着编辑他的答案让它完全回答这个问题,但我的编辑被拒绝了.

无论如何,这里是使Ember使用hashbang URL的完整代码:

(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;
    }

}));

})();
Run Code Online (Sandbox Code Playgroud)

然后,一旦您创建了应用程序,您需要更改路由器以使用"hashbang"位置实现:

App.Router.reopen({
    location: 'hashbang'
})
Run Code Online (Sandbox Code Playgroud)

  • 好的只是一些评论: - 最好重新打开`App.Router`而不是`Ember.Router`(所以你保持ember默认清理,特别是如果你正在测试) - 你不需要覆盖`init`和`willDestroy`,因为你扩展了HashLocation,这些函数将被继承,代码会更简单. (2认同)
  • 这个方法很有效,但是在最后一个ember抛出一个弃用消息; 如果不使用已弃用的代码,我们需要做些什么呢? (2认同)

Ted*_*nny 10

扩展Ember.HashLocation将是要走的路.

为了实现干净,您可以执行以下操作.

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...
})
Run Code Online (Sandbox Code Playgroud)

然后指示您的App Router使用您的自定义实现进行位置管理:

App.Router.reopen({
  location: 'hashbang'
})
Run Code Online (Sandbox Code Playgroud)