Using auto-remove
In some cases you want an event listener only to handle one event of a certain type. Imagine a user registers for an incentive on your site that he receives after he places an order. To implement this, you could add an event listener to the onOrder event that will trigger the needed database transactions or whatever is required.
But if the user places to orders, you want the incentive code executed only on his first order. To automatically achieve this, you can pass a third parameter to the addEventListener() method, which indicates, that the listener must be removed, after the event has been handled.
import net.schst.EventDispatcher.EventDispatcher; import net.schst.EventDispatcher.EventListener; EventDispatcher disp = EventDispatcher.getInstance(); // This listener is set to autoremove and will be // removed after it has handled the first event EventListener incentive = new IncentiveHandler(); disp.addListener("onOrder", incentive, true); disp.triggerEvent("onOrder"); // now the user places a second order // but the incentive handler has been executed // on the first event and removed afterwards disp.triggerEvent("onOrder");
This way it is extremely easy to handle events only the first time they occur.
AutoRemove? with global listeners
It is also possible to use the auto-remove feature in conjunction with global event listeners, which allows to only to catch the first event that is triggered, regardless of the event type.
import net.schst.EventDispatcher.EventDispatcher; import net.schst.EventDispatcher.EventListener; EventDispatcher disp = EventDispatcher.getInstance(); // This listener is set to autoremove and will be // removed after it has handled the first event EventListener debug = new DebugHandler(); disp.addGlobalListener(debug, true); // the global handler will only catch the first // event that is thrown disp.triggerEvent("onLogin"); disp.triggerEvent("onOrder");
