1

I got something for the javascript developers amongst us.

I got the following class:

function MyClass(){
    this.__defineSetter__("array", function(val){
        alert("setter called");
        this._array = val;
    });
    this.__defineGetter__("array", function(){
        alert("getter called");
        return this._array;
    });
    this._array = new Array();
};

Now, what happens is that when I execute

var a = new MyClass();
a.array[0] = "MyString";
alert(a.array[0]);

the getter is called twice (which is fine), but the setter is never executed, as the actual array reference does not change, only the content (I guess expected behavior). However, I'd also need to be "notified" when the array-content is modified. Thus, the call

a.array[0] = "MyString";

should also cause a setter-call (or something similar, important is to receive a notification when the array content has changed.

Anybody into this? How can this be achieved?

1 Answer 1

0

As we know,alert(a.array[0]); will only trigger a.array's getter/setter,and a.array[0] equal var p = a.array; p[0] which means what you want is trigger p[0]'s getter/setter,not just p's getter/setter. So,we can change our mind to this thinking:

add getter/setter to all items of p

so,we can do it like this:

  • if some like p[6] = 0 is used , which will trigger p's getter/setter , judge if all item of p has getter/setter .if not add it.
  • if some like p = [2,3,4] is use , simply first set getter/setter to the value.

and the code is: Jsfiddle

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.