Skip to content

Instantly share code, notes, and snippets.

@nbarthelemy
Created May 6, 2009 19:45
Show Gist options
  • Save nbarthelemy/107694 to your computer and use it in GitHub Desktop.
Save nbarthelemy/107694 to your computer and use it in GitHub Desktop.
var AbstractManager = Class.create({
__element_class: '',
__management_class: null,
initialize: function(element){
this.__instances = {};
this.__selected_instance = null;
this.__token = this.__element_class.replace('.','');
this.register(element ? $(element).select(this.__element_class) : $$(this.__element_class));
Object.extend(this, {
rpcListener: function(e){
var element = e.element();
if( !element.hasClassName(this.__token) )
element = element.up(this.__element_class);
var key = element.id;
var method = e.eventName.split(':').pop();
if( $H(this.__instances).keys().include(key) ) this[method](key);
}.bindAsEventListener(this)
});
document.observe(this.__token + ':set', this.rpcListener);
document.observe(this.__token + ':clear', this.rpcListener);
this.afterInitialize();
},
afterInitialize: function(){},
destroy: function(){
document.stopObserving(this.__token + ':set', this.rpcListener);
document.stopObserving(this.__token + ':clear', this.rpcListener);
},
register: function(element){
var _register = function(element){
element = $(element);
if( !element.id ) element.id = this.__token + '_' + String.random();
return this.__instances[element.id] = new this.__management_class(element);
}.bind(this);
return Object.isArray(element) ? element.collect(_register) : _register(element);
},
get: function(key){
if( key ){
if( typeof key == 'object'){
return this.__instances[$(key).up(this.__element_class).id];
} else {
return this.__instances[key];
}
} else {
return this.__selected_instance;
}
},
set: function(key){
return this.__selected_instance = this.get(key);
},
clear: function(){
this.__selected_instance = null;
},
send: function(method){
var values = $H(this.__instances).values();
if( values.length > 0 ) values.invoke(method);
},
setIds: function(){
this.send('setIds');
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment