dat.GUI 更改对象时不更新

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

问题描述:

有2个变量:

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

和一个control变量

control = controller1;

我将 dat.GUI 附加到 control.i

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

所以它显示 controller1.i 的值,当我更改 dat.GUI 中的值时,它会更改 controller1.i 的值。

之后,我运行:

control = controller2;

当我更改 dat.GUI 中的值时,我希望它更改 controller2.i,但现在它更改 controller1.i.

这是笔:http://codepen.io/kranzy/pen/QKzYAW

或堆栈片段:

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: (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.

问题是,通过调用 controller = gui.add(control, "i"),您传递了 control 对象(当前 controller1)的引用,并且 dat.gui 创建了该对象的内部副本参考。因此,如果您覆盖 ClickEventListener 中的 control,dat.gui 仍然保留对 controller1 的引用,并且 dat.gui 上的所有更改都倾向于 controller1。除了删除之前添加的控制器并传递一个新控制器外,我没有发现任何可能重置 dat.gui 中传递的引用。

我当时傻了...简直太简单了:

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

我在检查 dat.GUI 对象后发现了这种方式。

测试用例:http://codepen.io/anon/pen/aBvvmV