Skip to content

Instantly share code, notes, and snippets.

@inDream
Created June 17, 2013 11:57
Show Gist options
  • Save inDream/5796367 to your computer and use it in GitHub Desktop.
Save inDream/5796367 to your computer and use it in GitHub Desktop.
【Ember.js】使用History.js讓瀏覽器支援history API http://indreamhk.blogspot.com/2013/06/emberjs-historyjs.html
(function() {
var get = Ember.get, set = Ember.set;
var popstateFired = false;
/**
Ember.HistoryJsLocation implements the location API using History.js.
@class HistoryJsLocation
@namespace Ember RC5
@extends Ember.Object
*/
Ember.HistoryJsLocation = Ember.Object.extend({
init: function() {
set(this, 'location', get(this, 'location') || window.location);
this.initState();
},
initState: function() {
set(this, 'history', get(this, 'history') || window.History);
this.replaceState(this.formatURL(this.getURL()));
},
rootURL: '/',
getURL: function() {
var rootURL = get(this, 'rootURL'),
url = get(this, 'location').pathname;
rootURL = rootURL.replace(/\/$/, '');
url = url.replace(rootURL, '');
return url;
},
setURL: function(path) {
path = this.formatURL(path);
if (this.getState() && this.getState().path !== path) {
this.pushState(path);
}
},
replaceURL: function(path) {
path = this.formatURL(path);
if (this.getState() && this.getState().path !== path) {
this.replaceState(path);
}
},
getState: function() {
return get(this, 'history').getState().data;
},
pushState: function(path) {
get(this, 'history').pushState({ path: path }, null, path);
this._previousURL = this.getURL();
},
replaceState: function(path) {
get(this, 'history').replaceState({ path: path }, null, path);
this._previousURL = this.getURL();
},
onUpdateURL: function(callback) {
var guid = Ember.guidFor(this),
self = this;
Ember.$(window).on('popstate.ember-location-'+guid, function(e) {
if(!popstateFired) {
popstateFired = true;
if (self.getURL() === self._previousURL) { return; }
}
callback(self.getURL());
});
},
formatURL: function(url) {
var rootURL = get(this, 'rootURL');
if (url !== '') {
rootURL = rootURL.replace(/\/$/, '');
}
return rootURL + url;
},
willDestroy: function() {
var guid = Ember.guidFor(this);
Ember.$(window).off('popstate.ember-location-'+guid);
}
});
Ember.Location.registerImplementation('historyJs', Ember.HistoryJsLocation);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment