Skip to content

Instantly share code, notes, and snippets.

@seanmonstar
Created March 4, 2011 18:00
Show Gist options
  • Save seanmonstar/855399 to your computer and use it in GitHub Desktop.
Save seanmonstar/855399 to your computer and use it in GitHub Desktop.
Collapse.Stateful = new Class({
// or perhaps Collapse.Persistant?
Extends: Collapse,
options: {
getAttribute: function(element){
return element.get('id');
},
getIdentifier: function(element){
return 'collapse_' + element.get('id') + '_' + element.get('class').split(' ').join('_');
}
},
setup: function(){
this.key = this.options.getIdentifier.call(this, this.element);
this.state = this.getState();
this.parent();
},
prepare: function(){
var obj = this.state;
this.element.getElements(this.options.listSelector).each(function(element){
if (!element.getElement(this.options.childSelector)) return;
var state = obj[this.options.getAttribute.call(this, element)];
if (state == 1) this.expand(element);
else if (state == 0) this.collapse(element);
}, this);
return this.parent();
},
getState: function(){
return {};
},
setState: function(element, state){
var obj = this.state;
obj[this.options.getAttribute.call(this, element)] = state;
return this;
},
expand: function(element){
this.parent(element);
this.setState(element, 1);
return this;
},
collapse: function(element){
this.parent(element);
this.setState(element, 0);
return this;
}
});
Collapse.Cookie = new Class({
Extends: Collapse.Stateful,
getState: function(){
var that = this;
return Function.attempt(function(){
return JSON.decode(localStorage.getItem(that.key));
}) || {};
},
setState: function(element, state){
this.parent(element, state);
Cookie.write(this.key, JSON.encode(this.state), {duration: 30});
return this;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment