问题
Even if everything is in the title, to be clear, I would like my emberjs dynamic routes to look like:
http://mywebsite.com/#dynamic_route/subroute
with hash only, instead of the one with '/' by default:
http://mywebsite.com/#/dynamic_route/subroute
Not sure if it's possible (I tried several hacks without success) but if yes let me know :)
Thanks, Tom
回答1:
Up to version 1.0.0-pre.4 this seemed to be the default behaviour. In final version 1.0.0 it only behaves like this for routes without paths. An approach i have followed and seems to work fine is by providing an implementation for the location API (http://emberjs.com/guides/routing/specifying-the-location-api/) and it is based on the default implementation discussed in, https://github.com/emberjs/ember.js/issues/2053answers and Hashbang URLs using Ember.js
(function() {
var get = Ember.get, set = Ember.set;
Ember.Location.registerImplementation('no-slashes', Ember.HashLocation.extend({
getURL: function() {
var path = get(this, 'location').hash;
if(path.indexOf("/")!=1){
return "/"+path.substr(1);
}else{
return path.substr(1);
}
},
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(1);
if(path.indexOf("/")!=0){
path = "/"+path;
}
if (get(self, 'lastSetURL') === path) { return; }
set(self, 'lastSetURL', null);
callback(path);
});
});
}
}));
})();
App.Router.reopen({
location: 'no-slashes'
});
回答2:
@melc Thanks for pointing me in right direction. I improvised the code. Note - I am using ember 1.5.1.
I ended up overriding only getURL method. registerImplementation is deprecated in 1.5.1 so using the container to register the new implementation of HashLocation. Hope this helps someone.
(function() {
var get = Ember.get, set = Ember.set;
var noSlashLocation = Ember.HashLocation.extend({
getURL: function() {
var hash = this.getHash().substr(1);
return (hash.indexOf('/') != 0) ? '/'+hash : hash;
}
});
var container = new Ember.Container();
container.register('location:no-slash', noSlashLocation);
Ember.Router.reopen({
location: container.lookup('location:no-slash')
});
})();
来源:https://stackoverflow.com/questions/18511218/emberjs-dynamic-route-with-hash-only-no-slashes