Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
29
rated 0 times [  36] [ 7]  / answers: 1 / hits: 17158  / 12 Years ago, tue, december 11, 2012, 12:00:00

Possible Duplicate:

Javascript - How to extend Array.prototype.push()?






How can I be notified (run a pre-defined function) of any change to a registered array (or at least any addition or removal of elements)?
I tried using prototype. I don't want to be scolded for not providing SOME code examples of my own. So here's how I would like to use it.



var myArray = [];
myArray.bind(function() {
console.log('wtf'); // Wed Thu Fri and what were you thinking?
});


I don't need overkill. I basically know the Array function scope that I will be using (push, pop, splice and maybe a couple others). It's a way to use backbone's MVC. I want to run logic on an array and THEN have the views highlighted accordingly. But the view is already attached to a collection. Any change to that collection re-renders the actual DOM's in the view. I don't want that. I simple want to add, or remove, a class to the corresponding DOM's in the view for CSS purposes.


More From » arrays

 Answers
6

What I did is I made my own array type that just extended the prototype array, which then I added my own handlers to.



For example:



var MyArray = function() {
var arr = [];
arr.push = function() {
console.log(PUSHING, arguments);
return Array.prototype.push.apply(this, arguments);
}

return arr;
};


Usage:



var arr = new MyArray;
arr.push(12, 3, 45);
...


Fiddle: http://jsfiddle.net/maniator/vF659/


[#81486] Monday, December 10, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
breonnamayah

Total Points: 574
Total Questions: 115
Total Answers: 96

Location: England
Member since Sun, May 21, 2023
1 Year ago
;