Events decoupling demo
by ariehg
HTML
<script src="https://raw.github.com/arieh/Events/master/Events.js"></script>
JavaScript
//traditional
var obj = {
arr: [],
addEvent: function(fn) {
this.arr.push(fn);
},
fireEvent: function() {
var i, fn;
for (i = 0; fn = this.arr[i]; i++) fn();
}
};
var obj2 = {};
Events.call(obj2);
obj2.addEvent('bla', function(){console.log('a');});
obj2.addEvent('bla', function(){console.log(b);});//error - b is not defined
obj2.addEvent('bla', function(){console.log('c');});
obj.addEvent(function(){console.log('a');});
obj.addEvent(function(){console.log(b);});//error - b is not defined
obj.addEvent(function(){console.log('c');});
obj2.fireEvent('bla'); //a error c
obj.fireEvent(); //a error