3

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.

Community
  • 1
  • 1

2 Answers2

1

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

0

The problem is that by calling controller = gui.add(control, "i") you're passing the reference of the control object (current controller1) and dat.gui creates an internal copy of this reference. So if you overwrite the control inside the ClickEventListener dat.gui still holds the reference to controller1 and all changes on the dat.gui tends controller1. I didn't find any possibility to reset the passed reference in dat.gui except to remove previously added controller and pass a new one.

San Droid
  • 332
  • 1
  • 7
  • I know that already; `dat.GUI` holds an internal reference. And what I want is find any possibility to reset the passed reference in dat.gui without removing previously added controller and pass a new one. But thank you for answering this question. There must be a person answering this question or bounty will go to the trash. –  Nov 09 '16 at 01:14