Last active
December 26, 2015 12:59
-
-
Save korczis/7155089 to your computer and use it in GitHub Desktop.
PersistentObject = Ember.Object + HTML5 Local Storage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function (App) { | |
"use strict"; | |
App.reopen({ | |
PersistentObject: Ember.Object.extend({ | |
_impl: null, | |
// https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage | |
implementationDummy: { | |
getItem: function (sKey) { | |
if (!sKey || !this.hasOwnProperty(sKey)) { return null; } | |
return unescape(document.cookie.replace(new RegExp("(?:^|.*;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*((?:[^;](?!;))*[^;]?).*"), "$1")); | |
}, | |
key: function (nKeyId) { | |
return unescape(document.cookie.replace(/\s*\=(?:.(?!;))*$/, "").split(/\s*\=(?:[^;](?!;))*[^;]?;\s*/)[nKeyId]); | |
}, | |
setItem: function (sKey, sValue) { | |
if (!sKey) { return; } | |
document.cookie = escape(sKey) + "=" + escape(sValue) + "; expires=Tue, 19 Jan 2038 03:14:07 GMT; path=/"; | |
this.length = document.cookie.match(/\=/g).length; | |
}, | |
length: document.cookie.match(/\=/g).length, | |
removeItem: function (sKey) { | |
if (!sKey || !this.hasOwnProperty(sKey)) { return; } | |
document.cookie = escape(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/"; | |
this.length--; | |
}, | |
hasOwnProperty: function (sKey) { | |
return (new RegExp("(?:^|;\\s*)" + escape(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie); | |
} | |
}, | |
implementationReal: { | |
getItem: function (key) { | |
return localStorage.getItem(key); | |
}, | |
setItem: function (key, value) { | |
return localStorage.setItem(key, value); | |
}, | |
removeItem: function (key) { | |
return localStorage.removeItem(key); | |
} | |
}, | |
initialize: function () { | |
if (Modernizr.localstorage) { | |
this._impl = this.implementationReal; | |
} else { | |
this._impl = this.implementationDumy; | |
} | |
}, | |
get: function (key) { | |
if (!this._impl) { | |
this.initialize(); | |
} | |
return JSON.parse(this._impl.getItem(key)); | |
}, | |
set: function (key, value) { | |
if (!this._impl) { | |
this.initialize(); | |
} | |
return this._impl.setItem(key, JSON.stringify(value)); | |
}, | |
remove: function (key) { | |
if (!this._impl) { | |
this.initialize(); | |
} | |
return this._impl.removeItem(key); | |
} | |
}), | |
}); | |
// If you want access one persistent configuration via followin API: | |
// App.get('storage').get('key'); | |
// App.get('storage').set('key', 'value'); | |
// App.get('storage').remove('key'); | |
App.reopen({ | |
storage: App.PersistentObject.create({}) | |
}); | |
})(window.App); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment