hasharray / revaluate.js

non destructive code revaluation
https://revaluate.js.org
2 stars 0 forks source link

Enable lazy closures #1

Open caspervonb opened 8 years ago

caspervonb commented 8 years ago

Take the following example:

setTimeout(function tick() {
  var value = 0;

  setInterval(function tock() {
    console.log(value);
  });
});

Changing the value here, will have no effect as the capture has already happened.

A possible workaround for this, is to give every block a binding object, in which the generated code would behave similar to how function proxies work with a global backing object.

The generated code would look something like the following:

setTimeout(function tick() {
  binding[0].value = 0;

  setInterval(function tock() {
    console.log(binding[0].value);
  });
});

This way, we can also lazily set properties on it at runtime while traversing the tree, lets say an assignment operator.

var name = node.left.id.name;

Object.defineProperty(binding[0], name, {
  get: function() {
    delete binding[0][name];
    binding[0][name] = eval(code);

    return binding[0][name];
  },

  set: function(value) {
    delete binding[0][name];
    binding[0][name] = value;
  },
});