Reputation: 86747
I'm looking for a way to add some kind of parameter to an Event that is propagated using CDI events mechanism.
I know for my example I could just create different Events, but I'm looking for a way to reuse the same event, but with a different parameter. And then annotate some methods with this event parameter so that only this method gets invoked when the event is fired.
The following example does not work, but illustrates my intention. Is that somehow possible?
//custom event class
public class NotifyChange {
}
//change the model and notify the view
public class MyPresenter {
@Inject
private Events<NotifyChange> events;
public void updateUser() {
//change some user settings
events.fire(new NotifyChange("user")); //that what I'm somehow looking for
}
public void updateCustomer() {
//change some customer settings
events.fire(new NotifyChange("customer"));
}
}
//change the view according to events
public class MyView {
void listenUserChange(@Observes NotifyChange("user") evt) {
//update UI
}
void listenCustomerChange(@Observes NotifyChange("customer") evt) {
//update UI
}
}
Upvotes: 1
Views: 2843
Reputation: 2955
If you want to avoid creating classes and annotations for each event, I guess the best way is to use qualifier parameters. Here is what your code would look like:
//MyPresenter.class
@Inject @ChangeType(Role.USER)
private Event<NotifyChange> userEvent;
@Inject @ChangeType(Role.CUSTOMER)
private Event<NotifyChange> custumerEvent;
public void updateUser() {
userEvent.fire(new NotifyChange());
}
public void updateCustomer() {
custumerEvent.fire(new NotifyChange());
}
//MyView.class
public void listenUserChange(
@Observes @ChangeType(Role.USER) NotifyChange evt) {
}
void listenCustomerChange(
@Observes @ChangeType(Role.CUSTOMER) NotifyChange evt) {
}
//Role.class
public enum Role {
USER, CUSTOMER
}
//ChangeType
@Qualifier
@Target({ PARAMETER, FIELD })
@Retention(RUNTIME)
public @interface ChangeType {
Role value();
}
Further documentation: http://docs.jboss.org/weld/reference/1.1.5.Final/en-US/html_single/#d0e4018
Upvotes: 4