2017-03-02 222 views
0

我试图让自定义对象监听另一个自定义对象的事件。我怎样才能做到这一点?我做了一个病人和护士的小例子。当病人的尖叫声护士需要拿起电话并拨打911Javascript自定义对象需要监听另一个自定义对象事件

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!'); 

这工作,但现在我想有一个像警报内的护士的名字:

alert(this.Name + ' heard ' + sender.Name + ' scream.'); 

发件人相同,并输出:“约翰听到约翰尖叫。”。这很好,但我想让Jane听到John的尖叫声。我该如何解决这个JavaScript难题?

最好的问候, 雷米萨穆尔斯基

回答

1

我不认为你需要超时在Scream功能。但是,如果你这样做,看看这个:

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

如果您不需要超时:

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

UPD

现在我已经找到了解决办法。您需要将Nurse的背景传递给患者的OnScream

试试这个:

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

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

或关闭:

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

THX您的建议。已经尝试过两个例子,但仍然只有约翰听到自己尖叫,简仍然没有听到约翰尖叫。我用超时等待,直到这个.Scream函数在Jane的onScream响应之前结束。当我不使用超时时,在结束实际的this.Scream之前已经触发了“事件”。 –

+0

@ LiQuick.net回答更新 – MysterX

+0

非常感谢你,这两个解决方案的工作。我会看看这个_bind()_函数做了什么。谢谢! –