alvis

History.js polyfill for ember.js

Apr 5th, 2013
782
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. (function() {
  2.   var get = Ember.get, set = Ember.set;
  3.   var popstateFired = false;
  4.   Ember.HistoryJsLocation = Ember.Object.extend({
  5.     init: function() {
  6.       set(this, 'location', get(this, 'location') || window.location);
  7.       this._initialUrl = this.getURL();
  8.       this.initState();
  9.     },
  10.     initState: function() {
  11.       this.replaceState(this.formatURL(this.getURL()));
  12.       set(this, 'history', window.History);
  13.     },
  14.     rootURL: '/',
  15.     getURL: function() {
  16.       var rootURL = get(this, 'rootURL'),
  17.         url = get(this, 'location').pathname;
  18.       rootURL = rootURL.replace(/\/$/, '');
  19.       url = url.replace(rootURL, '');
  20.       return url;
  21.     },
  22.     setURL: function(path) {
  23.       path = this.formatURL(path);
  24.       if (this.getState() && this.getState().path !== path) {
  25.         this.pushState(path);
  26.       }
  27.     },
  28.     replaceURL: function(path) {
  29.       path = this.formatURL(path);
  30.       if (this.getState() && this.getState().path !== path) {
  31.         this.replaceState(path);
  32.       }
  33.     },
  34.     getState: function() {
  35.       return get(this, 'history').getState().data;
  36.     },
  37.     pushState: function(path) {
  38.       History.pushState({ path: path }, null, path);
  39.     },
  40.     replaceState: function(path) {
  41.       History.replaceState({ path: path }, null, path);
  42.     },
  43.     onUpdateURL: function(callback) {
  44.       var guid = Ember.guidFor(this),
  45.         self = this;
  46.       Ember.$(window).bind('popstate.ember-location-'+guid, function(e) {
  47.         if(!popstateFired) {
  48.           popstateFired = true;
  49.           if (self.getURL() === self._initialUrl) { return; }
  50.         }
  51.         callback(self.getURL());
  52.       });
  53.     },
  54.     formatURL: function(url) {
  55.       var rootURL = get(this, 'rootURL');
  56.       if (url !== '') {
  57.         rootURL = rootURL.replace(/\/$/, '');
  58.       }
  59.       return rootURL + url;
  60.     },
  61.     willDestroy: function() {
  62.       var guid = Ember.guidFor(this);
  63.       Ember.$(window).unbind('popstate.ember-location-'+guid);
  64.     }
  65.   });
  66.   Ember.Location.registerImplementation('historyJs', Ember.HistoryJsLocation);
  67. })();
Advertisement
Add Comment
Please, Sign In to add comment