Skip to content

Instantly share code, notes, and snippets.

@cpojer
Forked from ibolmo/Listener.js
Created February 9, 2011 01:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cpojer/817729 to your computer and use it in GitHub Desktop.
Save cpojer/817729 to your computer and use it in GitHub Desktop.
// Element Listener Mixin
(function(){
var property = '$listener';
var setup = function(element){
var listener = new Events, removeEvent = listener.removeEvent;
listener.removeEvent = function(key, value){
removeEvent.call(this, key, value);
element.removeEvent(key, value);
};
return listener;
};
this.Listener = new Class({
attach: function(key, value){
if (!this[property]) this[property] = setup(this.toElement());
this[property].addEvent(key, value);
this.toElement().addEvent(key, value);
}.overloadSetter(),
detach: function(key, value){
if (this[property]){
if (typeof key == 'string') this[property].removeEvent(key, value);
else this[property].removeEvents(key);
}
return this;
},
toElement: function(){
return this.element;
}
});
}).call(this);
// Implementation
var MyClass = new Class({
Implements: [Listener, Class.Binds],
initialize: function(){
this.element = new Element('div');
this.attach({
click: this.bound('onClick'),
'keyup:relay(:input)': this.bound('onKeyUp')
});
}
});
// Use
var myInstance = new MyClass();
myInstance.detach();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment