2017-12-28 10 views
0

내가 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

정확하게 이해했다면, 그 클래스를 동적으로 생성하려고합니다.

storeName 매개 변수를 사용하여 동적 관측 가능 함수와 설정 함수를 사용하여 저장소 클래스를 작성해야하는 래퍼 함수를 ​​만들었습니다. 이 같은

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() { ... } 
} 

는 도움이되기를 바랍니다.

+0

정확합니다. 마침내 클래스 대신 일반 JS 객체로 이동했지만 여전히 혼동하는 es6 클래스를 찾습니다. – amaurymartiny

관련 문제