I'm trying to have a custom object listen to an event of another custom object. How can I do this? I've made a small example of a patient and a nurse. When patient screams the nurse needs to pick up the phone and call 911.
function Patient(name) {
this.Name = name;
this.Scream = function (terribleSound) {
alert(terribleSound);
if (typeof this.OnScream === "function") {
setTimeout(this.OnScream(this), 1);
}
}
}
function Nurse(name, patient) {
this.Name = name;
this.Patient = patient;
this.Patient.OnScream = function (sender) {
alert(sender.Name + ' screamed');
}
}
var patient = new Patient('John');
var nurse = new Nurse('Jane', patient);
patient.Scream('AAAAAAAHHHHHHHHhhhhhh!');
This works but now I want to have the name of the nurse inside the alert like:
alert(this.Name + ' heard ' + sender.Name + ' scream.');
But this is the same as the sender and it outputs: "John heard John scream.". That's quite fine but I wanted Jane to hear John scream. How can I solve this JavaScript puzzle?
Best regards, Rémy Samulski