1

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.

2

2 Answers 2

0

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);
   }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Will try the second method. It seems interesting.
0

I think there is no native way of doing that. This topic was also discussed here and the suggested solution was to implement a wrapper class for your arrays.

Another way would be to only implement a wrapper push function and trigger the event on function call.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.