Created
September 23, 2014 09:26
-
-
Save jmas/7c06536621bb9a0e3387 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var originalPush = Array.prototype.push; | |
var Arr = function() { | |
var constr = new Array.prototype.constructor; | |
originalPush.apply(constr, arguments); | |
constr.events = []; | |
return constr; | |
}; | |
Arr.prototype = Array.prototype; | |
Arr.prototype.events = []; | |
Arr.prototype.on = function(eventName, handler) { | |
this.events.push({ | |
name: eventName, | |
handler: handler | |
}); | |
}; | |
Arr.prototype.trigger = function(eventName, args) { | |
args = args || []; | |
for (var i=0,len=this.events.length; i<len; i++) { | |
if (this.events[i].name == eventName) { | |
this.events[i].handler.apply(this, [args]); | |
} | |
} | |
}; | |
Arr.prototype.walk = function(handler) { | |
var oldValue, newValue; | |
var items = []; | |
for (var i=0,len=this.length; i<len; i++) { | |
oldValue = this[i]; | |
newValue = handler.apply(this, [oldValue, i]); | |
if (typeof newValue !== 'undefined') { | |
this[i] = newValue; | |
items.push({ | |
index: i, | |
oldValue: oldValue, | |
newValue: newValue | |
}); | |
} | |
} | |
this.trigger('changed', { | |
type: 'walk', | |
items: items | |
}); | |
return this; | |
}; | |
Arr.prototype.push = function() { | |
var result = originalPush.apply(this, arguments); | |
this.trigger('changed', { | |
type: 'push', | |
length: result, | |
args: arguments | |
}); | |
return result; | |
}; | |
var a = new Arr(1, 2, 3); | |
a.on('changed', function(e) { | |
console.log(e); | |
}); | |
console.log(a); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment