0

为了构建干净的代码,Famo.us 使用事件与模块进行通信。大多数事件指南都显示了有关EventHandler的示例。现在我们应该使用输入和输出事件构建健壮的视图,如何实际使用它?即输入和输出处理程序的目的是什么?

4

1 回答 1

1

为了构建健壮的模块,可以方便地将代码分成只负责构建它们的功能的小部件。这是构建小部件的官方方法:

function Widget(){
        this.eventOutput = new EventHandler();
        this.eventInput = new EventHandler();
        EventHandler.setInputHandler(this, this.eventInput);
        EventHandler.setOutputHandler(this, this.eventOutput);
    }

    var widget = new Widget();

总结上面的函数,它确实创建了一个带有 2 个 EventHandler 的对象,一个用于输入,另一个用于输出。

他们的目的是微不足道的:

  • 所有传入事件,即从小部件对象外部触发的事件将被触发到eventInput处理程序。
  • 所有传出事件,即小部件向外部生成的事件都是通过eventOutput触发的。

为了更好地理解,您很可能会从小部件内部侦听 eventInput 处理程序,并仍然从小部件代码内部触发 eventOutput 处理程序。

这是一个例子:

function Widget(){
        // here we are inside the Widget code scope
        var self = this; // just to keep the root "this" somewhere
        this.eventOutput = new EventHandler();
        this.eventInput = new EventHandler();

        this.eventInput.on("sayHello", function()
        {
            alert("Hello")
        });

        function didSomething()
        {
            self.eventOutput.trigger("didSomething");
        }
    }

然后,您可以按如下方式使用小部件:

var widget = new Widget();
widget.eventOutput.on("didSomething", function(){alert("The widget did something!")})
widget.eventInput.trigger("sayHello"); // will alert "Hello" from inside the widget

现在我们可能不愿意知道一个小部件的内部结构来使用它。在这里,我们正在调用和侦听实际上可能有任何名称的eventOutputeventInput 。为了代码的清晰,我们可以将这些事件函数绑定到小部件本身,在小部件中添加以下行:

... code ...
EventHandler.setInputHandler(this, this.eventInput);
EventHandler.setOutputHandler(this, this.eventOutput);
... code ...

现在可以通过以下方式监听和触发小部件:

widget.on("didSomething", function(){alert("The widget did something!")});
widget.trigger("sayHello"); // will let the widget alert "Hello"

管道呢?

这很简单,同时将 widgetA 传递给 widgetB

widgetA.pipe(widgetB);

触发的所有事件widgetA.eventOutput都通过管道传输(读取触发)到widgetB.eventInput

注意:同样的原则也可以应用在订阅上,下面会得到完全相同的结果:

widgetB.subscribe(widgetA);
于 2014-05-21T15:44:35.400 回答