LaVOZs

The World’s Largest Online Community for Developers

'; Reset a JavaScript Proxy object to default values - LavOzs.Com

I'm trying to manage state for a small application that has to be written in pure JS. I thought a proxy object would be the right fit, as I need to update various elements on the page when certain properties are updated.

Suppose I have this code:

Shared Setup for all Examples

const defaults = {
  foo: 'bar'
};

const state = { ...defaults };

Body of Code

const proxy = new Proxy(state, {
}); 

proxy.foo = 'baz'

We have a bare proxy that's not doing anything. But I want to implement a function or a trap that can reset all of the values of the proxied object back to the original defaults.

I'm imagining being able to call something like proxy.reset().

I've tried something like this, but it just doesn't seem to update the object:

const proxy = new Proxy(state, {
  get(target, prop) {
    if(prop == 'reset') {
      target = { ...defaults }
    }
  }
}); 

proxy.foo = 'baz'
proxy.reset

Any ideas? Do I need to use some other kind of object at the beginning? I'm trying to avoid simply setting the values manually, as the default object is likely to change as I develop. It feels like there should be an elegant way of doing this.

Would tell you are loosing a "pointer" setting target - you can set properties, but not change object by this.

const defaults = {
    foo: 'bar'
};

const state = { ...defaults };

const proxy = new Proxy(state, {
    get (target, prop) {
        if (prop === 'reset') {
            Object.assign(target, defaults);
            /*for (var i in defaults) {
                target[i] = defaults[i];
            }*/
        }
        if (prop === 'get') {
            return target;
        }
    }
});

proxy.foo = 'baz';
console.log(proxy.get);
proxy.reset;
console.log(proxy.get);