为类

时间:2017-12-28 12:16:13

标签: class factory mobx

我有10多个类(MobX商店,但不相关),它们共有90%的代码:

PriceStore.js

// Store to get the latest price of something
class PriceStore {
  @observable price;
  @observable error;

  constructor() {
    someSocket.on('price', this.setPrice);
    someSocket.on('price_error', this.setError)
  }

  static instance = null; // To enforce a singleton

  static get() {
    if (!PriceStore.instance) {
      PriceStore.instance = new PriceStore();
    }
    return PriceStore.instance;
  }

  @action setPrice = price => this.price = price;

  @action setError = error => this.error = error;
}

LatestUserStore.js

// Store to get the latest signed up user
class LatestUserStore {
  @observable latestUser;
  @observable error;

  constructor() {
    someSocket.on('latestUser', this.setLatestUser);
    someSocket.on('latestUser_error', this.setError)
  }

  static instance = null; // To enforce a singleton

  static get() {
    if (!LatestUserStore.instance) {
      LatestUserStore.instance = new LatestUserStore();
    }
    return LatestUserStore.instance;
  }

  @action setLatestUser = latestUser => this.latestUser = latestUser;

  @action setError = error => this.error = error;

  @computed get fullname() { ... }; // This store has an additional method.
}

我的问题是:如何将这90%的代码分解?

理想情况下,我想自己编写一个createMobxStore函数,以便我可以通过以下方式使用它:

const PriceStore = createMobxStore('price');
// Now I'll be able to use PriceStore as if it was defined like above.

const BaseLatestUserStore = createMobxStore('latestUser');
class LatestUserStore extends BaseLatestUserStore {
  @computed get fullname() { ... };
}
// Now I'll be able to use LatestUserStore as if it was defined like above.

如果可能的话,我想帮助编写这个createMobxStore函数。

1 个答案:

答案 0 :(得分:1)

如果我理解正确,您正在尝试动态创建该类。

我创建了一个包装函数,应该(未经测试)使用storeName参数创建该商店类,并使用动态可观察和setter函数。

function createStore(storeName) {

    return class Dynamic {
        @observable error;

        constructor() {
            // this[storeName];
            extendObservable(this, {
                [storeName]: null,
                ['set' + storeName]: action((value) => this[storeName] = value)
            })

            someSocket.on(storeName, this['set' + storeName]);
            someSocket.on('price_error', this.setError)
        }

        static instance = null; // To enforce a singleton

        static get() {
            if (!Dynamic.instance) {
                Dynamic.instance = new PriceStore();
            }
            return Dynamic.instance;
        }

        @action setError = error => this.error = error;
    }
}

并像这样使用它:

const UserStore = createStore('user');

class SomeStore extends UserStore {

    moreActions() { ... }
}

希望它有所帮助。