Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make Model Reactive and Observable #4

Open
pengVc opened this issue Jul 29, 2019 · 1 comment
Open

Make Model Reactive and Observable #4

pengVc opened this issue Jul 29, 2019 · 1 comment
Labels

Comments

@pengVc
Copy link
Owner

pengVc commented Jul 29, 2019

inspired by:

  • Object.defineProperty
  • MutationObserver

Usage:

/**
 * @typedef { Object } modelChanges
 * @property  { String } prop
 * @property  { * } oldValue
 * @property { * }  newValue
 */

const observer = new ReactiveModelObserver(function(changes){
  /**
   * @type { modelChanges } changes
   */
  console.log("something get changes:", changes);
});


const model = {};
observer.observe(model);

Implement:

class ReactiveModelObserver {

  constructor(reactiveCallback) {
    this.callback = reactiveCallback;
    this.storeModel = {};
    this.target = null;
  }

  observe(target = {}) {
    this.target = target;

    Object.keys(target).forEach((prop) => {
      this.storeModel[prop] = target[prop];

      Object.defineProperty(target, prop, {
        configurable: true,
        enumerable: true,
        get: () => this.storeModel[prop],
        set: (val) => {
          let oldValue = this.storeModel[prop];
          this.storeModel[prop] = val;
          this._notify({
            prop: prop,
            oldValue: oldValue,
            newValue: val
          });
        }
      });

    });
    
  }

  disconnect() {
    const { target } = this;

    Object.keys(target).forEach((prop) => {
      Object.defineProperty(target, prop, {
        value: this.storeModel[prop],
        configurable: true,
        enumerable: true,
        writable: true
      });
    });
    this.target = null;
    this.storeModel = null;
    return this;
  }

  _notify(mutation) {
    this._attemptExec(this.callback, [mutation]);
  }

  _attemptExec(fn, args, context) {
    if ("function" !== typeof fn) {
      return
    }
    return fn.apply(context, args);
  }

}
@pengVc pengVc added the draft label Jul 29, 2019
@pengVc pengVc added idea and removed draft labels Aug 8, 2019
@pengVc
Copy link
Owner Author

pengVc commented Aug 8, 2019

Usage Example:

const observer = new ReactiveModelObserver(function(changes){
  console.log("something get changes:", changes);
});

const  model = {
  name: "lily",
  age: 18,
  weight: "50kg"
};

observer.observe(model);
model.name = "lucy"
model.age = 20;
model.weight = "44kg";
console.log(`model: ${model.name} ${model.age} ${model.weight}`);

setTimeout(() => {
  console.log("unload reactive model:");
  
  console.log(`model: ${model.name} ${model.age} ${model.weight}`);
  observer.disconnect();

  model.weight = "42kg";
  console.log(`model: ${model.name} ${model.age} ${model.weight}`);
  console.log("nothing changes should fire")

}, 1e3);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant