evgeni fotia
evgeni fotia

Reputation: 4810

Proxy set a value

var context = {};
let head;
context.head = new Proxy({}, {
  get(obj, prop) {
    if (!head) {
      head = {
        htmlAttrs: {
          lang: 'Fr'
        }
      }
    }
    if (prop === 'htmlAttrs') {
      return `${JSON.stringify(head.htmlAttrs)}`
    }
  },
  set(obj, prop, value, rec) {
    return Reflect.set(...arguments);
  }
})
context.head.htmlAttrs = {
  key: true
}
console.log(context.head.htmlAttrs)

Now it log just lang: 'Fr' how to get it to log key: truetoo

Upvotes: 1

Views: 87

Answers (1)

NullDev
NullDev

Reputation: 7303

In this case, the obj variable returned by get() contains them:

var context = {};
let head;
context.head = new Proxy({}, {
  get(obj, prop) {
    if (!head) {
      head = {
        htmlAttrs: {

          // Include the properties
          ...obj.htmlAttrs,

          lang: 'Fr'
        }
      }
    }
    if (prop === 'htmlAttrs') {
      return `${JSON.stringify(head.htmlAttrs)}`
    }
    const text = prop in head ? head[prop].text() : ''
    return text && prop.endsWith('Attrs') ? ` ${text}` : text
  },
  set(obj, prop, value, rec) {
    return Reflect.set(...arguments);
  }
})
context.head.htmlAttrs = {
  key: true
}
console.log(context.head.htmlAttrs)

Upvotes: 1

Related Questions