Thursday, June 6, 2013

Google Closure - custom events in examples

Google Closure Library provides powerful handling system for managing events and listeners across browsers. Closure makes it possible to manage user-defined events too. With Google Closure Library you do not need to create your own Events system.


There are responsible classes in goog.event package. Headstones of google.event package are:
  • goog.events.listen()
  • goog.events.unlistenByKey(key);
  • goog.events.EventTarget
  • goog.events.Event
  • goog.events.EventHandler


Basic use
For basic use you make do with the function goog.events.listen(). Remove listener before destroying object is very important. You do not want memory leaks in your application. But hold reference to key it is inconvenient (read more). You could also be interested in the method goog.events.listenOnce().


Create custom event

The base event object is a goog.events.Event. If you build user defined events you will probably need to extend this class.

Create event target
An EventTarget is an object that can dispatch events. The most common example of an EventTarget is a DOM element but you can define your own EventTarget by inherit from class goog.events.EventTarget. You could also be interested that goog.events.EventTarget extends goog.Disposable. The object responsible for release object reference such as DOM nodes, COM object and register listeners. Subclass of goog.events.EventTarget can register listeners and dispatch events.

Manage listeners
Subclass of goog.events.EventHandler is useful in the release of listeners. After calling method dispose() it release all references to listeners. You can combine it with class goog.Disposable as mentioned bellow.