[proposal-idea] Variable decorators

# #!/JoePea (5 years ago)

Currently we can implement things like "reactive variables" and "reactive computations". Contrived example:

import {rv, computation} from './reactive-variable'

const count = rv(0)

// read the value
console.log(count()) // 0

// set the value
count(1)
console.log(count()) // 1

// increment it every second
setInterval(() => count(count() + 1), 1000)

// logs the value initially (1), and any time it is updated by the
interval after that.
computation(() => {
  console.log(count())
})

And we can do neat things like compile JSX to using reactive computations:

const div = <div>The count is: {count}</div>

document.body.append(div)

and now the div's textContent updates every second with the new value.

It'd be neat if we had variable accessors as well as variable decorators.

The above example could become:

import {rv, computation} from './reactive-variable'

// The rv variable decorator may implement this using a variable accessor
// We can already do this with class properties/fields when
transpiling class-based decorators
@rv const count = 0

// read the value
console.log(count) // 0

// set the value
count = 1
console.log(count) // 1

// increment it every second
setInterval(() => count++, 1000)

// logs the value initially (1), and any time it is updated by the
interval after that.
computation(() => {
  console.log(count)
})

const div = <div>The count is: {count}</div>

document.body.append(div)

variable accessors may look something like

// it is exportable just like regular variables
export let s {
  set(v) {
    console.log('set s:', v * 2)
    // maybe `this` is an engine-builtin object for this specific
variable, that we can use to store stuff on.
    this.s = v * 2
  },
  get() {
    console.log('get s:', this.s)
    return this.s
  },
} = 0

A variable decorator would have some way to be able to define a getter/setter.

# #!/JoePea (4 years ago)

Any one have any thoughts on this?