Black Dynamite
Black Dynamite

Reputation: 4147

JavaFX: How to listen for events on non-UI object

I've got a Model I call BlahModel. It's referenced by BlahController(BlahModel blahModel). My goal is that BlahModel can dispatch and event

Event.fireEvent(blahModel,...)

Which is heard by the BlahController to kick off jan action. As of now, I've been using an Observable Integer of somekind, and watching that but of course that doesn't feel right.

My question is, what on earth should a non-GUI component do to implement buildEventDispatchChain so other non-GUI components can listen to it.

Any help is GREATLY appreciated.

Upvotes: 0

Views: 382

Answers (1)

Tomas Mikula
Tomas Mikula

Reputation: 6537

EventDispatchChain is designed for events bubbling through a nested hierarchy (e.g. scene graph)—probably not what you want/need.

ReactFX's EventStream is an event analogy to ObservableValue:

import org.reactfx.EventSource;
import org.reactfx.EventStream;
import org.reactfx.Subscription;

class BlahModel {

    private EventSource<Integer> events = new EventSource<>();

    public EventStream<Integer> events() { return events; }

    void foo() {
        // fire event
        events.push(42);
    }
}

class BlahController {
    private final Subscription eventSubscription;

    BlahController(BlahModel blahModel) {
        eventSubscription = blahModel.events().subscribe(
                i -> System.out.println("Received event " + i));
    }

    public void dispose() {
        eventSubscription.unsubscribe();
    }
}

Upvotes: 2

Related Questions