By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,377 Members | 1,660 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,377 IT Pros & Developers. It's quick & easy.

Array object responding to changes

P: n/a
Is it possible to have an Array object (or an object derived from
Array) that is 'aware' of other code modifying its contents? I'd like
to have such an "onModify" function process an array everytime the []
operator is used to make a change. I know you can derive from Array,
but you cannot directly override the [] operator. Any way to make
this possible?

// possible definition of 'SpecialArray'
...
function OnModify()
{
// process the list
}

...

// an example of use
var myarray = new SpecialArray("zero", "one", "two", "three");
myarray[1] = "ein"; // this causes the array's OnModify to be
called
Thanks for any ideas.
bk
Jul 20 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
> Is it possible to have a JavaScript object that works just like a
standard Array, except that when the array is modified, a function
gets called which can then do some processing on the array?

Like this:
// SpecialArray has a function called Notify
function Notify()
{
// process the array with changes made
}
var myarray = new SpecialArray("zero", "one", "two", "three");
myarray[1] = "ein"; // after this change is made, function "Notify"
is called
I know you can derive a new object from Array, but you cannot directly
override the [] operator.

Can you add a function or event handler to a regular Array object that
gets called when the array changes?


No, put you can define a method that will have the effect you want, with a
different look perhaps. Make a constructor that takes two arguments: an array of
values, and an optional method to be called when changed.

function SpecialArray(array, method) {
this.get = function (index) {
return array[index];
};
this.put = function (index, value) {
array[index] = method ? method.apply(this, [index, this.get(index),
value]) : value;
};
}

The method you supply takes three parameters: The index, the old value, and the
new value. It should return the definitive new value (or the old value to leave
it effectively unchanged). This method can also do any notifications that you
need.

myarray = new SpecialArray(["zero", "one", "two", "three"], function (index,
older, newer) {
return newer;
});

Use myarray's privileged .get(index) and .put(index, value) methods to read and
write its contents.

myarray.set(1, "eine");

http://www.crockford.com/javacript/private.html
Jul 20 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.