I would like to use events to communicate between my objects in a google closure (GC) environment.
Suppose I have two classes foobar.Boss
and foobar.Employee
. The Boss wants to know when the Employee has made coffee, and whether or not that coffee is decaf (he's laying off the caffeine this week).
GC has made classes available that seem to provide the means to do this, goog.events.Event
and goog.events.EventTarget
.
Without knowing better, I'd think it would work like this:
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);
...
}
Is this a correct pattern? I am confused by the class goog.events.EventTarget
-- how does a target dispatch events? Doesn't a target have things happen to it?
This question is helpful, but a more direct answer would be appreciated.