The Echo.Component
object provides a built-in facility to manage event listeners and fire events. The addListener()
and removeListener()
methods allow for registration of arbitrary event types, and the fireEvent()
method is used to provide event notifications.
We'll again use the SpinButton
as an example, providing notification of an action
event when the user presses the ENTER key within the text field.
The Component
implementation will have a new method added, doAction()
, which notifies listeners of an action event:
doAction: function() { this.fireEvent({type: "action", source: this, actionCommand: this.get("actionCommand")}); }
The fireEvent()
method will look at the type
property of the object sent to it, and notify any registered listeners of that type. In this case, any action
listeners will be notified. Additionally we specify the source
property of the event, providing the this
reference to the the SpinButton
component itself. Also included in the event is the value of a new actionCommand
property of the component.
The Echo.Render.ComponentSync
of the SpinButton
will need to be updated to receive notification when the ENTER key is presssed in the text field and subsequently notify the Component
implementation.
To do this, we'll first create an event handler for called _processKeyUp()
which will handle any keyup
events in the text input field. This method will check if the ENTER key (character code 13) was pressed, and if so, notify the SpinButton
component:
_processKeyUp: function(e) { if (e.keyCode == 13) { this.component.doAction(); } },
And to invoke the above code when key up events are received, we'll update the renderAdd()
method to register a keyup
listener with the DOM:
Core.Web.Event.add(this._input, "keyup", Core.method(this, this._processKeyUp), false);
You'll of course also want to unregister the event listener when the synchronization peer is disposed. But looking at our Example.SpinButton.Sync
class' renderDispose()
implementation, the necessary code is already present, as it's being used to remove other DOM listeners:
Core.Web.Event.removeAll(this._input);