Home > Software design >  What are the ways of intercepting setting of property on an object?
What are the ways of intercepting setting of property on an object?

Time:06-16

I'm trying to figure out how the setting of a property is being intercepted in jsdom's CSSStyleDeclaration implementation. This is being done for validation purposes. I want to know where this validation is happening. github link

This is the line where the setting is happening. this[lowercaseName] = value;

I'm only aware of one method that can be used to intercept this action. Which is usage of Proxy Object. But the object in question is not a proxy object.

Hence Question: What are the other ways of intercepting(man in the middle) the action of setting properties on an object?

To confirm interception is happening:

const {CSSStyleDeclaration} = require('cssstyle')
const decl = new CSSStyleDeclaration()

decl.setProperty('background-color', 'invalid-value')

decl.getPropertyValue('background-color') // '' returns empty string

decl.setProperty('background-color', '#333')

decl.getPropertyValue('background-color') // '#333'

Use can use this IDE

CodePudding user response:

What are the other ways of intercepting(man in the middle) the action of setting properties on an object?

Setters!

The set syntax binds an object property to a function to be called when there is an attempt to set that property.

In your particular example the colour validation is done by a parseColor function called by the background-color setter.

  • Related