Correct way to connect ValueTree to Components created at runtime?


#1

Hi fellow JUCERS,

I’m having a hard time figuring out the most elegant way to ‘connect’ child Components which have been added to a PluginEditor at runtime, to the nodes of a corresponding ValueTree in such a way as to keep both ‘in sync’ with each other whilst enforcing a reliable and predictable data structure inside the ValueTree.

I find it easy to understand how to connect a fixed number of Components defined at compile time, to a correspondingly fixed number of ValueTree nodes/properties, but when the GUI requires that various Components have child Components added/removed at runtime, and nodes in the ValueTree also correspondingly added/removed, I find it much harder to get my head around.

I’ve been working on a plugin for a while, and when I initially tackled this problem, I came up with the following solution:

  • each GUI Component maintains a reference to its node in the ValueTree
  • the ValueTree is wrapped in a PresetManager class which acts as a centralised interface to the ValueTree to ensure that only a limited set of allowable changes can be made
  • each GUI Component listens directly to the PresetManager’s ValueTree and updates itself / adds / removes children accordingly

However having since discovered this thread on ValueTreeAttachments and with the newly added CachedValue class templates, I’m convinced that there’s a better approach.

So, what is the idiomatic solution to this problem? Any input greatly appreciated!

Also, what is the name of the architectural pattern discussed in @daniel & @olilarkin’s ValueTreeAttachments thread? My attempts to learn more by Googling phrases like “GUI attachment software architecture” have come up empty, so I assume it must go by another name…?


#2

Hi @willrice,
I don’t know, if there is a term for two objects mutually synchronizing each other. However, the basis is called “subject-observer pattern”, which means an observer (your component) registers a callback (being a listener) to the subject (the valuetree). That is more or less a shortened form of the later, more prominent “model view controller pattern”, which only adds the controller for the behaviour / interaction.

The attachments as I implemented them (I think the original ones go the same way) uses additionally a member flag to avoid infinite callbacks. An alternative to that is to check, if the value changes before calling the callback (but watch out for rounding problems, or if you use a “snapToLegalValue”, like a step size on a slider or parameter).

I’m sorry that I don’t comment on your initial question about what is correct and incorrect, I’m not the one to judge that. And many ways lead to Rome.