Loi Nguyen Huynh
Loi Nguyen Huynh

Reputation: 9938

How to interupt Array.push with Proxy?

I want to add a side effect every when an array being pushed. For example, I want to add console.log:

var arr = [];
arr.push(1); // => I want it to work normally, and in addition, it logs 1 to the console

How to achieve that? I'm looking for a solution using Proxy and I have tried handler.get() and handler.apply() but still, can't figure it out.

Upvotes: 0

Views: 886

Answers (3)

BCDeWitt
BCDeWitt

Reputation: 4773

To directly answer your initial question...you need to return a closure from the get trap. To actually trap this, you would need to use proxy.push() instead of array.push(), though. For example:

const arr = [];

const arrProxy = new Proxy(arr, {
  get(target, prop) {
    if (prop === 'push') {
      return (...args) => {
        console.log(...args);
        return target[prop](...args);
      };
    }
    return target[prop];
  }
});

arrProxy.push('test');
arrProxy.push('test1', 'test2');

Upvotes: 3

Loi Nguyen Huynh
Loi Nguyen Huynh

Reputation: 9938

Here's the final answer that I'm comfortable with, it doesn't use Proxy by the way.

{

var arr = [];

// add push
arr.push = function (...items) {
  console.log(...items);
  Array.prototype.push.apply(this, items);
};

arr.push('test');
arr.push('test1');

// clean up the push
delete arr.push;

}

Upvotes: 1

Mister Jojo
Mister Jojo

Reputation: 22320

something like that ?

Object.defineProperty(Array.prototype, 'myPush',
  {
  value : function (...val)
    {
    console.log(...val)
    return this.push(...val)
    }
  })


let aa = []
aa.myPush( 5,123)

console.log('aa = ', aa  )
 

Upvotes: 0

Related Questions