canjs / can-observable-mixin

Define properties on JavaScript classes
https://canjs.com
MIT License
2 stars 1 forks source link

Value behaviors that do not resolve should not retain their old value when unbound #128

Closed phillipskevin closed 5 years ago

phillipskevin commented 5 years ago

There is a strange asymmetry between value behaviors that call resolve and ones that don't when the properties are unbound.

Take this example:

class Obs extends ObservableObject {
  static props = {
    prop: String,
    count: {
      value({ listenTo, resolve }) {
        let count = resolve(0);
        listenTo("prop", () => resolve(++count));
      }
    },
    counter: {
      value({ listenTo, resolve }) {
        listenTo("prop", ({ value }) => resolve(value));
      }
    }
  };
}

const obs = new Obs();

If you bind both properties and change prop, they both resolve with a new value:

obs.listenTo("count", ({ value }) => {
  console.log(`count changed to ${value}`);
});
obs.listenTo("counter", ({ value }) => {
  console.log(`counter changed to ${value}`);
});

obs.prop = "Hi";  // -> "count changed to 1"
                             // "counter changed to Hi"

If you then make both properties unbound and then read them, the property calling resolve will be reset, but the property that doesn't call resolve will retain its old value:

obs.stopListening();

obs.count; -> 0
obs.counter; -> "Hi"