Here's an example from the upcoming
toxiclibs release, demonstrating usage of the already existing EventDispatcher helper class:
- import toxi.util.events.*;
- // our demo class to emit custom events
- DemoEventBroadcaster ticker;
- // a demo event receiver to change background color when events are received
- BgUpdater bg;
- // another event receiver to toggle a text display
- DemoLabel label;
- void setup() {
- size(200,200);
- // create instances
- bg=new BgUpdater();
- label=new DemoLabel("hello");
- // configure broadcaster to emit an event every 500ms
- ticker=new DemoEventBroadcaster(500);
- // attach listeners
- ticker.dispatcher.addListener(bg);
- ticker.dispatcher.addListener(label);
-
- textFont(createFont("SansSerif",24));
- }
- void draw() {
- ticker.update();
- // use current bg color from BgUpdater
- background(bg.col);
- label.draw();
- }
- // this interface defines the actual event listener capabilities
- // each method defined in here is a possible event:
- // in this case each listener implementation only needs to provide a single tick() method
- interface DemoEventListener {
- void tick();
- }
- // this event listener changes the background color
- // with each event notification
- class BgUpdater implements DemoEventListener {
- int col;
-
- // event callback
- void tick() {
- col=(int)random(0xffffff);
- }
- }
- // this event listener toggles the display of a text label
- // with each event notification
- class DemoLabel implements DemoEventListener {
- boolean isEnabled;
- String txt;
-
- DemoLabel(String txt) {
- this.txt=txt;
- }
-
- // event callback
- void tick() {
- isEnabled=!isEnabled;
- }
-
- void draw() {
- if (isEnabled) {
- fill(255);
- textAlign(CENTER);
- text(txt,width/2,height/2);
- }
- }
- }
- // actual event generator to which our listeners above are subscribed to
- // uses the generic EventDispatcher helper class in toxi.util.events package
- // this class generated events at a regular time interval configured in the constructor
- class DemoEventBroadcaster {
-
- public EventDispatcher<DemoEventListener> dispatcher=new EventDispatcher<DemoEventListener>();
-
- long lastEvent;
- long period;
-
- DemoEventBroadcaster(long period) {
- this.lastEvent=System.currentTimeMillis();
- this.period=period;
- }
-
- void update() {
- long now=System.currentTimeMillis();
- if (now-lastEvent>=period) {
- for(DemoEventListener l : dispatcher) {
- l.tick();
- }
- lastEvent=now;
- }
- }
- }
http://postspectacular.com |
http://toxiclibs.org