我正在尝试设置我的路由器使用“hashbang”URL(#!
)。
我尝试过这个,但显然它不起作用:
App.Router.map(function() {
this.route("index", { path: "!/" });
this.route("otherState", { path: "!/otherState" });
});
在Ember中能做到这个吗?
我正在尝试设置我的路由器使用“hashbang”URL(#!
)。
我尝试过这个,但显然它不起作用:
App.Router.map(function() {
this.route("index", { path: "!/" });
this.route("otherState", { path: "!/otherState" });
});
在Ember中能做到这个吗?
registerImplementation
似乎是实现这一点的一种清晰方式。我试图编辑他的答案以完全回答该问题,但我的编辑被拒绝了。(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;
}
}));
})();
创建应用程序后,您需要更改路由器以利用“hashbang”位置实现:
App.Router.reopen({
location: 'hashbang'
})
App.Router
而不是 Ember.Router
(这样您可以保持 Ember 默认设置的清洁,特别是在测试时)init
和 willDestroy
,这些函数将被继承,代码会更简单。扩展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...
})
然后指示您的应用路由使用您自定义的位置管理实现:
App.Router.reopen({
location: 'hashbang'
})
registerImplementation
。这绝对使它更清晰。我编辑了你的答案,包括完整的代码,以使其工作,因为除了formatURL
中的更改之外,还必须进行其他几个更改。 - twiz
Ember.HashLocation
属性并向多个字符串添加一些“!”来使其正常工作。我不确定这是否会导致任何问题。如果没有更好的方法,我将把我的代码作为答案添加。 - twiz