LiQuick.net
LiQuick.net

Reputation: 199

Javascript custom object needs to listen to another custom objects event

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

Upvotes: 0

Views: 35

Answers (1)

MysterX
MysterX

Reputation: 2368

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.');
    };
}    

Upvotes: 1

Related Questions