我想使用事件在Google關閉(GC)環境中的對象之間進行通信。使用Google關閉創建事件
假設我有兩個類foobar.Boss
和foobar.Employee
。老闆想知道員工何時煮咖啡,以及該咖啡是否是無咖啡因的(他本週正在放棄咖啡因)。
GC已經提供了可用類,似乎提供了這樣做的手段,goog.events.Event
和goog.events.EventTarget
。
不知道更好,我認爲它會像這樣工作:
foobar.Employee.prototype.makeCoffee = function(isDecaf)
{
this.coffeeMaker.putCoffeeInMachine(isDecaf);
this.coffeeMaker.start();
var event = new goog.event.Event('COFFEE_ON', { isDecaf: isDecaf });
goog.events.dispatchEvent(event);
}
foobar.Boss.prototype.addEmployee = function(employee)
{
...
goog.events.listen(employee, 'COFFEE_ON', function(e)
{
if (e.target.isDecaf)
{
this.refillMug();
}
}, false, this);
...
}
這是一個正確的模式?我很困惑goog.events.EventTarget
- 目標如何派遣事件?目標沒有發生嗎?
This question很有幫助,但更直接的答案將不勝感激。
http://code.google.com/p/closure-library/source/browse/trunk/closure/goog/fx/fx.js?r=2 #582是一個示例實現 - 從goog.events.EventTarget繼承似乎很奇怪(Employee是否完全需要擴展EventTarget?) – 2012-01-31 23:40:13