javascript - 使用谷歌闭包创建事件

标签 javascript google-closure

我想在 google 闭包 (GC) 环境中使用事件在我的对象之间进行通信。

假设我有两个类 foobar.Bossfoobar.Employee。老板想知道员工什么时候煮过咖啡,以及咖啡是否不含咖啡因(他这周要戒掉咖啡因)。

GC 提供的类似乎提供了执行此操作的方法,goog.events.Eventgoog.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很有帮助,但更直接的答案将不胜感激。

最佳答案

看了一段时间后,我现在的理解是 EventTarget 实际上扮演着双重 Angular 色,既是调度事件的实体,又是被监听的实体。所以一个选择是让 Employee 继承 goog.events.EventTarget 但我走了一条不同的路。

首先,我创建了一个新的事件类型,让老板知道咖啡是否不含咖啡因。

/**
 * @constructor
 * @extends {goog.events.Event}
 */
foobar.CoffeeEvent = function(isDecaf)
{
  goog.events.Event.call(this, 'COFFEE_ON');
  this.isDecaf = isDecaf;
};
goog.inherits(foobar.CoffeeEvent, goog.events.Event);

接下来我创建了一个事件监听器类型来分派(dispatch)这些事件。

/**
 * @constructor
 * @extends {goog.events.EventTarget} 
 */
foobar.CoffeeEventTarget = function()
{
  goog.events.EventTarget.call(this);
};
goog.inherits(foobar.CoffeeEventTarget, goog.events.EventTarget);

我向我的 Employee 添加了一个这种类型的对象。

foobar.Employee = function()
{
  ...
  this.coffeeEvents = new foobar.CoffeeEventTarget();
  ...
}

当员工重新装满咖啡时:

foobar.Employee.prototype.makeCoffee = function(isDecaf)
{        
    this.coffeeMaker.putCoffeeInMachine(isDecaf);
    this.coffeeMaker.start();
    var event = new foobar.CoffeeEvent(isDecaf);
    this.coffeeEvents.dispatchEvent(event);
}

先生。老板听这个。

foobar.Boss.prototype.addEmployee = function(employee)
{
    ...
    goog.events.listen(employee.coffeeEvents, 'COFFEE_ON', function(e)
    {
        if (e.isDecaf)
        {
            this.refillMug();
        }
    }, false, this);
    ...
}

请注意,这不会告诉我哪个员工给咖啡加满了咖啡,因为事件目标将是 CoffeeEventTarget 的一个实例。如果你想要所有的 Employee ,我想你可以将它添加为成员字段。如果您同意从 goog.events.EventTarget 继承到 Employee,那么您可以免费获得 Employee 作为目标。

关于javascript - 使用谷歌闭包创建事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9088165/

相关文章:

javascript - 为什么这行谷歌闭包看起来像?

google-closure - 如何为 Google Closure Compiler 自动生成 extern

javascript - Sequelize 中的 .sync() 到底是做什么用的?

javascript - jQuery .when 未按预期与休息运算符一起工作

javascript - Node.js post请求本地文件

javascript - Angular UI 路由器 - 状态查询字符串参数不起作用

google-closure-compiler - Google Closure Builder - 防止 base.js 插入

javascript - 如何强制谷歌闭包编译器保留 "use strict";在编译的js代码中?

JavaScript with Ajax with HTTP request outputs undefined display 2