Skip to main content

Command Palette

Search for a command to run...

JavaScript: Attach a event listener to an Array which gets triggered when an item is pushed into the array.

Updated
1 min read
JavaScript: Attach a event listener to an Array which gets triggered when an item is pushed into the array.
H

Full stack developer (ReactJS, NodeJS, JavaScript, PHP, SQL)

let includeEventTriggerToArray = function(inputArr, callback) {
    inputArr.push = (element) => {
        console.log('Pushed Item', element);
        Array.prototype.push.call(inputArr, element);
        callback(inputArr);
    };
};


let inputArr = [1, 2];
inputArr.push(3);

includeEventTriggerToArray(inputArr, function(updatedArr) {
  console.log('Triggered on array push');
  console.log('----------------------------------------');
}); 

inputArr.push(4); 
inputArr.push(5);
Output:

Pushed Item 4
Triggered on array push
----------------------------------------
Pushed Item 5
Triggered on array push
----------------------------------------

Execute above code here

More from this blog

E

Everyday Dev Patterns

26 posts

A collection of real-world JavaScript snippets, patterns, and gotchas from my day-to-day work.