DEV Community

Discussion on: A practical guide to Javascript Proxy

Collapse
 
drozerah profile image
Drozerah • Edited

Hi Thomas!
I'm currently experimenting a way to implement an Object observer with an ES6 class and today I've discovered the ES6 Proxy so I decided to use it (see below) but I'm not really confident in what I've achieved...It works but is it relevant ? Thank you for your feed back if you can and for your nice article!

What I wanted is to call a method each time this.input.value changes in other words observing the Object...

class Myclass {

    constructor(){

        this.input = {

            value: 10
        }
        this.Proxy = new Proxy( this.input, {

            set: (target, prop, value) => {

                this.displayInputValue(target[prop], value)

                target[prop] = value

                return true
            }
        })
    }

    displayInputValue(from, to){

        console.log(`this.input.value changed from ${from} to ${to}`)
    }

    init(){

        let counter = 0
        setInterval(() => {

            counter ++
            this.Proxy.value = counter
        }, 1000)
    }
}

const initMyClass = new Myclass().init()