var DelegatesDemo = new Class({
Implements: Options,
options: {
typeSelector: 'click:relay(li)',
delegator: 'parent',
log: 'log'
},
initialize: function(options){
this.setOptions(options);
this.delegator = document.id(this.options.delegator);
this.log = document.id(this.options.log);
this.bound = this.logDelegateeText.bind(this);
this.attach();
},
attach: function(){
this.delegator.addEvent(this.options.typeSelector, this.bound);
return this;
},
detach: function(){
this.delegator.removeEvent(this.options.typeSelector, this.bound);
},
logDelegateeText: function(event, element){
var text = element.get('text');
this.log.set('text', text);
}
});
window.addEvent('domready', function(){
var demo = new DelegatesDemo();
$('add_item').addEvent('submit', function(event){
event.stop();
var newText = $('new_text');
new Element('li',{
html: newText.value
}).inject('parent', 'top');
newText.select();
});
$('detach').addEvent('click', function(){
demo.detach();
$('attach').set('disabled', false);
});
$('attach').addEvent('click', function(){
demo.attach();
$('detach').set('disabled', false);
});
});
<form id="add_item">
<input id="new_text" type="text" value="New Item Text" /> <input type="submit" value="Add New Item" />
</form>
<h2 id="log">Waiting for you to click an item ...</h2>
<ul id="parent">
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
<hr/>
<button id="detach">Detach</button> <button id="attach" disabled="disabled">Attach</button>