2

I have an object

const app ={
    el: "#app",
    data: {
        some: "test"
    }
}

Any time I want to add something to the data, be it app.data.some = "changed" or app.data.other = "new" I want something to happen.

Things I tried

Using a Proxy. I have a feeling the answer is somewhere in here:

const data ={
    el: "#app",
    data: {
        some: "test"
    }
}

var app = new Proxy(data, {
  get: function (target, prop) {
    console.log(prop); // just shows data
    return Reflect.get(target, prop);
  },
  set: function (target, prop, value) {
    // this never runs
    console.log({ type: "set", target, prop, value });
    return Reflect.set(target, prop, value);
  },
});

app.data.another = "test";
app.data.something

And the following is just to say I know about it but it doesn't seem to be what I want as there's no way to add new properties. I'm trying to get this effect my where the property is unknown.

const app = {
  el: "#app",
  data: {
    _another: "testing", 
    get another() {
      console.log("get something");
      return this._something;
    },
    set another(value) {
      console.log("set something", value);
      this._something = value;
    }
  },
};
 
app.data.another = "test";
app.data.another
relidon
  • 2,142
  • 4
  • 21
  • 37
  • Is this a vue object? it looks very much like one. vue adds getters and setters for you. it also provides for "watch" functions. – danh Apr 28 '22 at 17:51
  • @danh influenced by it. I'm trying to explore js by trying to "clone" vue in my own way – relidon Apr 28 '22 at 19:06

0 Answers0