0

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

1 Answer 1

1

I don't think you need a timeout in Scream function. But if you do, look at this:

this.Scream = function (terribleSound) {
    alert(terribleSound);
    if (typeof this.OnScream === "function") {
        setTimeout(function(){this.OnScream(this)}.bind(this), 1);
    }
}

If you don't need timeout:

this.Scream = function (terribleSound) {
    alert(terribleSound);
    if (typeof this.OnScream === "function") {
        this.OnScream(this);
    }
}

UPD

Now I have found the solution. You need to pass context of Nurse to patient's OnScream.

Try this one:

function Nurse(name, patient) {
    this.Name = name;
    this.Patient = patient;

    this.Patient.OnScream = function (sender) {
        alert(this.Name + ' heard ' + sender.Name + ' scream.');
    }.bind(this);
}

or with closure:

function Nurse(name, patient) {
    var self = this;
    this.Name = name;
    this.Patient = patient;

    this.Patient.OnScream = function (sender) {
        alert(self.Name + ' heard ' + sender.Name + ' scream.');
    };
}    
Sign up to request clarification or add additional context in comments.

2 Comments

Thx for your suggestions. Have tried both examples but still only John hears himself scream and Jane still doesn't hear John scream. I used the timeout to wait until the this.Scream function ended before Jane's onScream reaction to it. When I don't use the timeout the "event" is already triggered before ending the actual this.Scream.
Thank you very much, both solutions work. I'll have a look what this bind() function does. THX!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.