Learn How To Be Transparent Learn How To Be Transparent - 1 month ago 13
Javascript Question

dat.GUI doesn't update when I change the object

Description of the problem:



There are 2 variable:

controller1 = {i: 100};
controller2 = {i: 300};


and a
control
variable

control = controller1;


I attached dat.GUI to
control.i
.

gui = new dat.GUI();
controller = gui.add(control, "i");
controller.listen();


So it displays the value of
controller1.i
and when I change value in dat.GUI, it changes value of
controller1.i
.

After that, I run:

control = controller2;


When I change the value in
dat.GUI
, I want it to change
controller2.i
, but right now it changes
controller1.i
.

Here is the pen: http://codepen.io/kranzy/pen/QKzYAW

or Stack Snippets:



controller1 = {i: 100};
controller2 = {i: 300};
control = controller1;
click.addEventListener("click", function() {
control = control == controller1 ? controller2:controller1;
});
gui = new dat.GUI();
controller = gui.add(control, "i");
controller.listen();
setInterval(function (){
current.textContent = JSON.stringify(control);
x.textContent = JSON.stringify(controller1);
y.textContent = JSON.stringify(controller2);
},1000/24)

<script src="https://cdnjs.cloudflare.com/ajax/libs/dat-gui/0.6.1/dat.gui.min.js"></script>
<h1>Controller 1: <code id="x"></code></h1>
<h1>Controller 2: <code id="y"></code></h1>
<button id="click"><h1>Change controller</h1></button>
<h1>Value of current controller: <code id="current"></code></h1>






The only way I can see is deleting the controller and init it again everytime I change
control
variable, but I want to know another way.


That way is suggested here: Refreshing dat.gui variable (not really the same as my question, but related).

If you don't know anything about
dat.GUI
, you can take the tour here and see if you can help me.

Answer

I was stupid... It's as easy as hell:

click.addEventListener("click", function() {
  control = control == controller1 ? controller2:controller1;
  controller.object = control;
  // change the internal reference in dat.GUI
});

I found that way after inspecting the dat.GUI object.

Test case: http://codepen.io/anon/pen/aBvvmV