Skip to content

Instantly share code, notes, and snippets.

@cv
Created January 12, 2015 21:55
Show Gist options
  • Save cv/2b6798e5d1741fbde950 to your computer and use it in GitHub Desktop.
Save cv/2b6798e5d1741fbde950 to your computer and use it in GitHub Desktop.
array-listeners.js
Array.prototype.addEventListener = function(fn, cb) {
if(!this.__eventListeners) {
this.__eventListeners = {};
}
if(typeof(fn) !== 'string') {
throw "Can't add event listener: 1st argument is not a string";
}
if(typeof(cb) !== 'function') {
throw "Can't add event listener: 2nd argument is not a function";
}
if(!this[fn]) {
throw "Can't add event listener: Array has no method " + fn + " defined";
}
if(!this.__eventListeners[fn]) {
this.__eventListeners[fn] = [];
}
this.__eventListeners[fn].push(cb);
};
['push', 'pop', 'shift', 'unshift'].forEach(function(fn) {
var old = Array.prototype[fn];
Array.prototype[fn] = function() {
var args = arguments, self = this;
try {
return old.apply(this, args);
} finally {
if(this.__eventListeners && this.__eventListeners[fn]) {
this.__eventListeners[fn].forEach(function(cb) {
cb.apply(self, args);
});
}
}
}
});
var a = [1,2,3];
a.addEventListener('push', function(i) {
console.log('pushed ' + i + ' to ' + this);
});
a.addEventListener('pop', function(i) {
console.log('popped from ' + this);
});
a.addEventListener('shift', function(i) {
console.log('shifted ' + this);
});
a.addEventListener('unshift', function(i) {
console.log('unshifted ' + i + ' from ' + this);
});
console.log(a.push(4));
console.log(a.pop());
console.log(a.push(5));
console.log(a.shift());
console.log(a.unshift(0));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment