Gist-ES6-Proxy

Introduction

"Proxy" is a frequently used pattern in both virtual world and real world. Those patterns("proxy", "iterator" and "observer",etc) make coding more personably, as if we're building lots of maganificent skyscrapers with robust methods and tools.

Basic concept

Single request

Interaction

Application - Observer

// Create an observer to detect the opening state of light
const basicState = {
    open: false
}
const lightState = new Proxy(basicState, {
    set(obj, prop, value) {
        if (prop === 'open') {
            switch(value) {
                case true: 
                    console.log('Light on!')
                    break
                case false: 
                    console.log('Light off!')
            }
        }

        return true
    }
})


// Turn on light
lightState.open = true    // output: Light on!

// Turn off light
lightState.open = false    // output: Light off!

Grammar

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy

Conclusion

Try Proxy? Trust it at first

Thanks for your reading. Welcome to subscribe my blog by Github.

Post Time: 2017/7/13
Category: Technology/FrontEnd/JavaScript
Author all rights reserved reprint please indicate the source no commercial reprint
Copyright © 2017-2021Terry SuALL RIGHTS RESERVED