I'm currently enrolled in a course and I'm delving into the mechanics of callbacks between two classes. To aid my understanding, I have crafted this example:
function Car() {
this.offer = {};
this.OfferUpdate = () => {
this.callback(this.offer)
}
this.callback = function(){};
this.Listener = (callback) => {
this.callback = callback;
}
}
var car = new Car();
car.offer = {
model: ['A4', 'A5', 'A6'],
engine: ['TDI', 'TFSI']
}
class Car_showroom {
constructor() {
this.model = ['A4'];
this.engine = ['TDI'];
car.Listener((newItems) => {
// Callback logic here
this.model = newItems.model
this.engine = newItems.engine
})
}
}
let car_showroom = new Car_showroom();
let p = document.createElement("p")
let p2 = document.createElement("p")
let text = document.createTextNode("car.offer: " + JSON.stringify(car.offer));
let text2 = document.createTextNode("car_showroom: " + JSON.stringify(car_showroom))
p.appendChild(text);
document.body.appendChild(p);
p2.appendChild(text2);
document.body.appendChild(p2);
car.OfferUpdate(); // Invoking callback
let p3 = document.createElement("p")
let text3 = document.createTextNode("car_showroom after car.OfferUpdate(): " + JSON.stringify(car_showroom))
p3.appendChild(text3);
document.body.appendChild(p3);
Upon triggering the car.OfferUpdate()
, the associated callback within the method is activated, subsequently initiating the listner()
method. However, I am puzzled as to how.
How exactly does executing this.callback(this.offer)
lead to the invocation of the listner()
method?