cocopon / tweakpane

:control_knobs: Compact GUI for fine-tuning parameters and monitoring value changes
https://tweakpane.github.io/docs/
MIT License
3.52k stars 87 forks source link

Receive the previous value on change event #115

Closed aarongeorge closed 3 years ago

aarongeorge commented 3 years ago

It would be helpful to add a second parameter to the change callback so that you receive the previous value.

Is anyone opposed to this?

E.g.

const PARAMS = { index: 0 }

const pane = new Tweakpane()

pane.addInput(PARAMS, 'index', {
    step: 1,
    min: 0,
    max: 100
}).on('change', (newValue, previousValue) => {

    // If `index` was `0` and has been changed to `1`
    // `newValue` = 1
    // `previousValue` = 0
    console.log(newValue, previousValue)
})
cocopon commented 3 years ago

I think it would be useful in some situations but not suitable for general use. For example, previous values for MouseEvent (clientX, clientY, etc.) may also be useful but have not been implemented.

We also have to consider the second argument. (ref: #110) Maybe some kind of (ev: SomeTweakpaneEvent) => void would be better for this case.

cocopon commented 3 years ago

FYI, you can do it with one simple function like this:

const params = {
  foo: 50,
  bar: '#f00',
};

const pane = new Tweakpane();

// Create a handler that stores a previous value
function handlePrev(handler) {
  let prevValue = undefined;

  return (newValue) => {
    handler(newValue, prevValue);
    prevValue = newValue;
  };
}

pane.addInput(params, 'foo', {
  min: 0,
  max: 100,
  step: 1,
}).on(
  'change',
  handlePrev((newValue, prevValue) => {
    console.log(`[foo] new: ${newValue}, prev: ${prevValue}`);
  })
);

pane.addInput(params, 'bar').on(
  'change',
  handlePrev((newValue, prevValue) => {
    console.log(`[bar] new: ${newValue}, prev: ${prevValue}`);
  })
);
LeonardoRick commented 7 months ago

I think knowing the previous value of each bind would be really useful to implement a "undo" logic!