Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I trigger a callback when an object attribute is modified?

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?

like image 836
Neil Avatar asked Dec 17 '22 13:12

Neil


2 Answers

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);
like image 132
Andrey Khoronko Avatar answered Dec 27 '22 21:12

Andrey Khoronko


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.

like image 32
Code Maniac Avatar answered Dec 27 '22 21:12

Code Maniac