Array Event Listener
Array.prototype.listeners = {};
Array.prototype.addListeners = function (eventName, callback) {
if (!this.listeners[eventName]) {
this.listeners[eventName] = [];
}
this.listeners[eventName].push(callback);
};
Array.prototype.pushWithEvent = function (...args) {
this.push(...args);
this.listeners["pushWithEvent"].forEach((cb) => {
cb(args);
});
};
Array.prototype.popWithEvent = function () {
let value = this.pop();
this.listeners["popWithEvent"].forEach((cb) => {
cb(value);
});
};
const arr = [1, 2, 3];
arr.addListeners("pushWithEvent", (values) => {
console.log("Items added: " + values);
});
arr.addListeners("pushWithEvent", (values) => {
console.log("Items added again: " + values);
});
arr.addListeners("popWithEvent", (value) => {
console.log("Item removed: " + value);
});
arr.addListeners("popWithEvent", (value) => {
console.log("Item removed again: " + value);
});
arr.pushWithEvent(4, 5, 6);
arr.popWithEvent();
console.log(arr);
// Items added: 4,5,6
// Items added again: 4,5,6
// Item removed: 6
// Item removed again: 6
// [1, 2, 3, 4, 5]