ValueTree property Value listener not being called

Hi, sorry if I’m missing something obvious but I’m trying to add a listener to a ValueTree property (not the whole tree, just a single property) but it is never being called.

This is a boiled down version of my code:

class ValueTestComponent : public juce::Component, public Value::Listener
{
 public:
	ValueTestComponent() : valueTree(Identifiers::appState)
	{
		setSize(600, 400);

		valueTree.setProperty(Identifiers::comboValue, 2, nullptr); //Create a property in the ValueTree
		auto comboValue = valueTree.getPropertyAsValue(Identifiers::comboValue, nullptr); //Get that property as a value
		comboValue.addListener(this); //Try to listen to changes to this value
		
		//Hook up a combo box to the property to change it via the UI
		addAndMakeVisible(comboBox); 
		comboBox.addItemList(StringArray{ "one", "two", "three" }, 1);
		comboBox.getSelectedIdAsValue().referTo(comboValue);

		//Add a label which will also show changes to the property
		addAndMakeVisible(label);
		label.getTextValue().referTo(comboValue);
	}

	void valueChanged(Value& value) override
	{
		//This is never called
		DBG("Value changed to " << value.toString());
	}

 private:
	ValueTree valueTree;
	ComboBox comboBox;
	Label label;
};

As the comments state I have a ValueTree with one property connected up to a combo box and a label, which my component is also a listener to. When I change the value of the property via the combo box the label updates correctly but the listener is never called.

This is on Mac OS with Juce v7.0.4

Any advice on what I’m doing wrong would be greatly appreciated.

The comboValue where you attach the listener to goes out of scope, hence no callback.
Try to make the comboValue a member and it should work. To connect them, use referTo:

comboValue.addListener (this);
comboValue.referTo (valueTree.getPropertyAsValue(Identifiers::comboValue, nullptr));

If you added the listener first, referTo will also trigger an initial valueChanged() callback.

2 Likes

Of course! Thanks so much for the quick response :clap: