How to update a gui's display from an object's properties?

I can control an object’s properties from a gui. For example, if my scene has a cube, I can update cube.position.z from a gui.

function initGui(){
  const gui = new dat.GUI();
  const cubePositionFolder  = gui.addFolder('cube')
  cubePositionFolder.add(cube.position, 'z', -LIMIT, LIMIT);
}

The problem is that I don’t see how to tell the gui to update its display if an object it references has changed.

Illustrated by this fiddle:

https://jsfiddle.net/fiddleuser03/4ed7bgwj/43/

cube.position.z is constantly changing. Adjusting z in the gui will change the cube position. The gui however seems to have no knowledge of any changes to the cube properties.

I was expecting there to be something like gui.update() that could go in the render function.
Looking at https://github.com/dataarts/dat.gui/blob/f720c729deca5d5c79da8464f8a05500d38b140c/API.md however, I don’t see any such method.

How would I achieve this?

You can use .listen() to make the GUI auto update when the objects property has changed.

There are more usefull methods like .updateDisplay() that might be what you are looking for.

Also there is an .onChange() method for triggering a callback when the property changes.

Just have a look at the documentation.
You can chain these methods to keep code handy.

Example:

cubePositionFolder.add(cube.position, 'z', -LIMIT, LIMIT).listen().onChange(
   function(){
      console.log(cube.position.z)
   }
)
2 Likes

Thanks @Drumstructor, that’s very helpful.

I’ve made a little demo of that technique.
https://jsfiddle.net/fiddleuser03/mx26r9pc/10/