0

Here is an Array var arr = [1, 2, 3],I want to implement an method to observe the array changes. It likes

arr.on('change', function () {
    // to do something
});

It will automatic trigger the 'change' event when I push or delete data from array.

Is it possible? How can I do it?

Thank you

3
  • No, it's not possible. Events only occur on DOM elements. Commented Oct 10, 2013 at 12:56
  • 1
    see here stackoverflow.com/questions/5306843/… might be useful for u Commented Oct 10, 2013 at 12:56
  • I'm confused now. Is array a DOM ELement? Commented Oct 10, 2013 at 12:58

1 Answer 1

0

That's the first idea that came to my head:

var arr = [1, 2, 3],
    tmp = [].slice.apply(arr);

setInterval(function() {
    if (arr.join() !== tmp.join()) {
        console.log("Changed");

        tmp = [].slice.apply(arr);
    }
}, 10);

Or the prototype version:

Array.prototype.change = function(callback) {
    var _this = this,
        tmp = [].slice.apply(_this);

    setInterval(function() {
        if (_this.join() !== tmp.join()) {
            callback();

            tmp = [].slice.apply(_this);
        }
    }, 10);
};

var arr = [1, 2, 3];
arr.change(function() {
    console.log("Changed!");
});
arr.push(4); // Changed!
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.