Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
192
rated 0 times [  195] [ 3]  / answers: 1 / hits: 39061  / 16 Years ago, sat, february 21, 2009, 12:00:00

I'm trying to extend the Array.push method so that using push will trigger a callback method and then perform the normal array function.


I'm not quite sure how to do this, but here's some code I've been playing with unsuccessfully.


arr = [];
arr.push = function(data){

//callback method goes here

this = Array.push(data);
return this.length;
}

arr.push('test');

More From » arrays

 Answers
45

Since push allows more than one element to be pushed, I use the arguments variable below to let the real push method have all arguments.


This solution only affects the arr variable:


arr.push = function () {
//Do what you want here...
return Array.prototype.push.apply(this, arguments);
}

This solution affects all arrays. I do not recommend that you do that.


Array.prototype.push = (function() {
var original = Array.prototype.push;
return function() {
//Do what you want here.
return original.apply(this, arguments);
};
})();

[#99944] Monday, February 16, 2009, 16 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jadyngraysons

Total Points: 455
Total Questions: 109
Total Answers: 98

Location: Trinidad and Tobago
Member since Fri, May 8, 2020
4 Years ago
jadyngraysons questions
Thu, Apr 23, 20, 00:00, 4 Years ago
Sat, Jan 18, 20, 00:00, 4 Years ago
Tue, Dec 31, 19, 00:00, 4 Years ago
;