Array change listener

Adrian Bartholomew picture Adrian Bartholomew · Dec 11, 2012 · Viewed 14.4k times · Source

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.

Answer

Naftali aka Neal picture Naftali aka Neal · Dec 11, 2012

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/