Skip to content

Instantly share code, notes, and snippets.

@rmanalan
Created November 21, 2010 04:02
Show Gist options
  • Save rmanalan/708435 to your computer and use it in GitHub Desktop.
Save rmanalan/708435 to your computer and use it in GitHub Desktop.
Fix for sammy.store.js
Sammy.Store = function(options) {
var store = this;
this.options = options || {};
this.name = this.options.name || 'store';
this.element = this.options.element || 'body';
//this.$element = $(this.element); // <== *** Don't redefine $element here... do it below...
if ($.isArray(this.options.type)) {
$.each(this.options.type, function(i, type) {
if (Sammy.Store.isAvailable(type)) {
store.type = type;
return false;
}
});
} else {
this.type = this.options.type || 'memory';
}
this.meta_key = this.options.meta_key || '__keys__';
this.storage = new Sammy.Store[Sammy.Store.stores[this.type]](this.name, this.element, this.options);
};
Sammy.Store.stores = {
'memory': 'Memory',
'data': 'Data',
'local': 'LocalStorage',
'session': 'SessionStorage',
'cookie': 'Cookie'
};
$.extend(Sammy.Store.prototype, {
// Checks for the availability of the current storage type in the current browser/config.
isAvailable: function() {
if ($.isFunction(this.storage.isAvailable)) {
return this.storage.isAvailable();
} else {
true;
}
},
// Checks for the existance of `key` in the current store. Returns a boolean.
exists: function(key) {
return this.storage.exists(key);
},
// Sets the value of `key` with `value`. If `value` is an
// object, it is turned to and stored as a string with `JSON.stringify`.
// It also tries to conform to the KVO pattern triggering jQuery events on the
// element that the store is bound to.
//
// ### Example
//
// var store = new Sammy.Store({name: 'kvo'});
// $('body').bind('set-kvo-foo', function(e, data) {
// Sammy.log(data.key + ' changed to ' + data.value);
// });
// store.set('foo', 'bar'); // logged: foo changed to bar
//
set: function(key, value) {
var string_value = (typeof value == 'string') ? value : JSON.stringify(value);
key = key.toString();
this.storage.set(key, string_value);
if (key != this.meta_key) {
this._addKey(key);
this.$element = $(this.element); // <== *** Redefine $element here so trigger below will work
this.$element.trigger('set-' + this.name, {key: key, value: value});
this.$element.trigger('set-' + this.name + '-' + key, {key: key, value: value});
};
// always return the original value
return value;
},
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment