Starmaster
Starmaster

Reputation: 862

extending existing method

So, I have a lot of places with code, when I push some elements to array:

arr.push(...)

But the problem is, that I would like to run custom code after each push. Basically the question is not only about this example. What I want to do is something like this:

func1.func2(...);

After this I want to run another function which will get all things, which func2 did and for example log it. But these functions in code are a lot and it is not desirable to write something like this every time:

if (func1.func2(...)) {
   log_results();
}

Instead, for every func1.func2() I want automatically run another separate function, which will get results and log it.

Upvotes: 2

Views: 71

Answers (4)

Starmaster
Starmaster

Reputation: 862

Actually gforce301 code helped me. I was dealing with Google dataLayer and the task was to log all push data (except some). This code snippet helped me:

var dataLayer_copy = dataLayer.push;
dataLayer.push = function() {
  dataLayer_copy.apply(this, arguments);
  console.log(JSON.stringify(arguments));
  $.post('/log', {data: arguments}, function() {

  }, 'json');
};

Upvotes: 0

gforce301
gforce301

Reputation: 2984

This is an interesting question. There are plenty of libraries like Lodash that do similar things to functions. Like methods that return copies of functions with arguments partially applied: _.curry. I tested it and it works on Array.prototype.push.

Doing some research I found this post with this answer: JavaScript: clone a function and decided to try to do what you wanted without making the clone method.

Here is what I came up with. Replace the console.log with a call to any function you like or any other code you wish.

Array.prototype.push = (function() {
    var old = Array.prototype.push;
    var push = function () {
        console.log('my new push where I can do what I want, like log some stuff'); 
        return old.apply(this, arguments)
    };
    return push;
})();

var foo = [];
foo.push(1,2,3);
console.log(foo);

Upvotes: 1

Kyle Richardson
Kyle Richardson

Reputation: 5645

You could add another prototype to Array that uses push inside and then whatever else you want to execute.

let testArr = [];

Array.prototype.pushPlusStuff = function(val) {
   this.push(val);

   console.log("executing other stuff here");
};

testArr.pushPlusStuff("test");

console.log(testArr);

This will make the .pushPlusStuff method available to all Arrays

Upvotes: 0

Brennan
Brennan

Reputation: 5732

The only way to really accomplish this is to wrap it in a function that does the extra work you want.

function pushAndLog(item) {
  arr.push(item);
  // Additional Code here
  logResults();
}

Upvotes: 3

Related Questions