简体   繁体   中英

Aurelia Proxy does not fire setter

js proxy setter does not get fired in aurelia. I have a config that I inject in my components:

const config = { prop: 'value' };
export default new Proxy(config, {
   get: function(obj, prop) {
      console.log('get ' + prop + ' = ' + obj[prop]);
      return obj[prop];
   },
   set: function(obj, prop, value) {
      console.log('set ' + prop + ' = ' + value);
      obj[prop] = value;
      return true;
   },
});

The getter fires when I change a property, but the setter function is not executed, even though the value in the config object changes.

Your issue isn't an Aurelia problem, you're using a Proxy the wrong way. I have thrown together an example of a proxy setter and getter being used.

If you open up the developer console in Chrome, you can try the following code out in your browser. The important thing to note is to work with the returned proxy, not the original object. You need to work with the proxy.

let config = { prop: 'value' };
let configProxy = new Proxy(config, {
   get: function(target, property) {
      return target[property];
   },
   set: function(target, property, value) {
      if (value.length > 3) {
        target[property] = value;
      } else {
        throw new ReferenceError(property + ' cannot be set');
      }
   }
});

// Setting a value less than 3 characters will trigger an error
configProxy.prop = 'D';

// This is fine
configProxy.prop = 'Dwayne';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM