Object Destruction
HTML
<button id="new">New Box</button>
<button id="clear">Clear</button>
<button id="fire">Fire!</button>
<div id="boxes"></div>
<div id="console"></div>
CSS
.box {
border:1px solid #FFF;
background:#F00;
color:#FFF;
padding:5px;
}
.box.even {
background:#0F0;
}
JavaScript
var Mediator = new Class({
Implements: [Events],
initialize: function () {},
fire: function (k, v) {
$('console').grab(new Element('hr'));
$('console').grab(new Element('p[text="Firing \"' + k + '\""]'))
this.fireEvent(k, v);
}
});
var Box = new Class({
initialize: function () {
this.id = String.uniqueID();
this.element = new Element('div.box[text="Box"]');
this.bound = {
fire: this.onFire.bind(this)
};
context.mediator.addEvent('fire', this.bound.fire);
},
destroy: function () {
this.element.destroy();
context.mediator.removeEvent('fire', this.bound.fire);
},
onFire: function () {
$('console').grab(new Element('p[text="Heard \"fire\""]'))
},
toElement: function () {
return this.element;
}
});
var context = {};
context.mediator = new Mediator();
context.boxes = {};
$('new').addEvent('click', function () {
var box = new Box();
$('boxes').grab(box);
context.boxes[box.id] = box;
});
$('clear').addEvent('click', function () {
// $('boxes').empty();
console.log(context.boxes);
Object.each(context.boxes, function (box) {
try {
box.destroy();
delete box;
} catch (e) {
alert(e);
}
//delete context.boxes[box.id];
});
$('console').empty();
});
$('fire').addEvent('click', function () {
context.mediator.fire('fire', {});
console.log(context.boxes);
});