If I have a class like:
class Myclass {
constructor(){
this.a = [];
this.sum = 0;
}
update(){
this.sum = this.a.reduce((a, b) => a + b, 0)
}
}
I instantiate the class:
myClass = new Myclass();
I append a number to the a
attribute
myClass.a.push(1);
myClass.a.push(2);
How can I call the update method every time the a
attribute is modified? In other words, how can I trigger a callback when an object attribute is altered?
Add method for pushing new items to the a
array, e.g:
class Myclass {
constructor(){
this.a = [];
this.sum = 0;
}
update(){
this.sum = this.a.reduce((a, b) => a + b, 0)
}
pushItem(val) {
this.a.push(val);
this.update();
}
}
myClass = new Myclass();
myClass.pushItem(1);
myClass.pushItem(2);
console.log(myClass.sum);
One way is to extend Array
and shadow the push
method.
class MyArray extends Array{
constructor(ref){
super();
this.ref = ref
}
push(value){
super.push(value)
this.ref.update()
console.log("called")
}
}
class Myclass {
constructor(){
this.a = new MyArray(this);
this.sum = 0;
}
update(){
this.sum = this.a.reduce((a, b) => a + b, 0)
}
}
let myClass = new Myclass()
myClass.a.push(1);
myClass.a.push(2);
console.log(myClass.sum)
P.S:- Certainly not a good idea to call the callback on each insertion if you're not using the sum value after insertion.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With