Vaadin lets you build secure, UX-first PWAs entirely in Java.
Free ebook & tutorial.
CustomComponents, initialization and missed listeners
I'm looking for a pattern that I can't figure out myself.
I have a CustomComponent that is a user controlled widget. For illustration's sake, let's say I'm doing my own flavor of Select. To give the component a defined state, I initialize it with, say, the first selectable item in the Select. The user can then select another item, and the component fires events whenever the selection is changed.
Does anyone have ideas for a convenient way to get a listener added before the initialization selection occurs?
Let me illustrate:
MyAwesomeSelectionComponent select = new MyAwesomeSelectionComponent(); layout.addComponent(select); MyEvenAwesomerListener listener = new MyEvenAwesomerListener(); select.addListener(listener);
By the time the Listener is added, the initialization has (normally) already occurred in the constructor. One way would be to give the listener as a constructor parameter, but that gets ugly quickly if you want to add several 'initial' listeners. It's not very Vaadin-y anyways.
What I have previosly done is to create my own addListener() method that takes also a boolean argument, and if it's true, the current value is fired immediately back to the listener. But that seems like a bit hack-y, too, since that's not how normal Vaadin addListener() methods look like.
Is there a hook in a Component that would be called after the constructor, but before the rendering phase, where I could safely and reliably initialize the component, so that all listeners can hear what it's doing?
Quickly from the top of my head:
Call the listener immediately with the initial value iff the component has not yet been painted for the first time.
Also note that attach() would almost allow you to do what you want - but only "almost", because it will usually be called when you add the component to the layout, so the listeners would only be called if they are added before that, which would certainly lead to hard-to-catch bugs.
Actually both have sort of the same problem: behavior depends on timing - the first solution is just (IMHO) less likely to cause problems (if you add a listener anytime later, after the component was first painted, it will not trigger an event = potential wtf).
edit: Summing up: in the end, your boolean solution might be the most explicit and least error-prone solution...