Correct MVC approach for communication between classes of a custom component in JavaFX 2
-
15-07-2021 - |
题
I have a custom JavaFX-2
component written in the fxml
language (Which I'll referrer as child or children), which I used the JavaFX Scene Builder
to create it. One of my view classes need to display several (~100) of those components and communicate with them. With the MVC
architecture in mind, what's the best approach for communication?
- (Container) Model -> (Children) Model
- (Container) Controller -> (Children) Controller
- (Container) Controller -> (Children) Model
Basically I need at least to be able to monitor 2 case of events happening in the children UI and or in the container object.
Case 1: The user clicked a button (or interacted with another object) which exists inside my custom component (child), the container must be communicate about the change.
Case 2: The user triggered an event on the container, filtering the components based on a specific query for example, I need to communicate the children about this change.
Thanks in advance for all the help. Cheers
解决方案
I always tend to keep communication between the controllers, while my models are POJOs although they use javafx properties to store data. This seems to map to option #2.
It is fairly easy for the parent controller to call the child controller, all it has to do is load them and keep them in a list. The child calling the parent is a little more ugly since it might require a reference to the parent. I try and avoid this by having an event handler property on the child controller which the parent adds a listener to. This has made my child controls quite reusable.