Search code examples
javascriptarraysdom-eventscustom-events

Generating event on Javascript array


How can I generate an event when contents of a Javascript array is modified i.e. an event should be generated when push or pop operations are performed over that particular Javascript array. Basically, I want to track the push, pop operations performed over a particular Javascript array.

Edit :- The solutions which are stated in comments, requires to override the push or pop method. I want to perform it without doing overriding it.


Solution

  • The idea is that Arrays are Objects so you can define properties.

    var someArray = []; // a normal array
    
    someArray.push = function() { // this will override the original push method
      // custom code here
      console.log('pushing something..');
      return Array.prototype.push.apply(this, arguments); // original push
    };
    // now everytime you push something a message will be logged. Change this functionality as you like.
    

    Note: someArray.push() will now be enumerable. If you want to prevent this you can define a 'push' property using Object.property method.

    Object.defineProperty(someArray, 'push', {
      enumerable: false, // it's false by default anyway
      value: function() {
        console.log('pushing something..');
        return Array.prototype.push.apply(this, arguments);
       }
    });