2016-05-04 23 views
2

このクラスでは、初期化されたブール状態を使用してMobx.autorunの実行を行います。 Otherwize 'this'は完全に割り当てられておらず、エラーにつながります。これを行う別の方法がありますか?クラスコンストラクタでの発火を防ぐためにMobx.autorunを生成する方法は?

class GameMaster{ 

    private _initialized:boolean = false; 
    private _store:IDomainStore; 
    private _moveDisposer:Lambda; 

    /** 
    * 
    * @param store - client or server store 
    */ 
    constructor(store:IDomainStore){ 
     this._store = store; 
     console.log(this._store); 
     //todo abstract services to decouple client device from GameMaster because it is also used on the server. 
     this._moveDisposer = autorun(()=>{ 
      // prevent firing in the constructor 
      if(this._initialized) { 
      this.present(
       <IIntent>{ 
       fromId: 'GeoLocation.service', 
       toIds: [Meteor.userId()], 
       wish: actions.playerActions.types.CHANGE_PLAYER_GEO_COORDINATES, 
       data: [System.GeolocationService.coordinates.lng, System.GeolocationService.coordinates.lat] 
      }); 
      } 
     }); 
     this._initialized = true; 
     } 

    public present(intent:IIntent):boolean{ 
     ... 
    } 
... 
} 

これは、別のファイルの私の観測可能である:私はしかし、初期化されたフィールドも同様に観察する必要があり、これが問題に細かなアプローチだと思う

@observable coordinates = { 
    lng:0, 
    lat:0 
    }; 
+0

どの変数が観察可能なものとして装飾されているかを指定できますか?私はオートランがあなたの現在のセットアップではまったく起動しないと期待します。 – mweststrate

+0

そして、 'coordinates'はおそらく建設中に実際に起動されるか、あるいは自動実行が初期化目的のために一度実行されるのでしょうか? – dagatsoin

答えて

3

。それ以外の場合は、_initializedを変更しても、自動実行は再実行されません。

しかし、この場合、自動実行後の最初のステートメントがtrueに初期化されるため、初期化された変数が正確に何を達成するのかわかりません。

私はあなたが達成したいことは完全にはわかりません:自動実行/ presentをコンストラクタの呼び出しを延期するか、最初のpresent呼び出しをスキップすることを延期しますか?

更新答え

あなたは副作用(この場合はpresentを送信)を防止したい場合は、そのための単純なパターンがあります。手掛かりは、副作用に必要な値を計算することを確認することですが、副作用は自分で引き起こさないようにしてください。だからあなたの例では、これは

constructor(store:IDomainStore){ 
    let firstRun = true; 
    this._moveDisposer = autorun(()=>{ 
     // make sure all information is tracked 
     const presenceInfo = <IIntent>{ 
      fromId: 'GeoLocation.service', 
      toIds: [Meteor.userId()], 
      wish: actions.playerActions.types.CHANGE_PLAYER_GEO_COORDINATES, 
      data: [System.GeolocationService.coordinates.lng, System.GeolocationService.coordinates.lat] 
     } 
     // but prevent the side effect in the first run 
     if(!firstRun) { 
      this.present(presenceInfo); 
     } else { 
      firstRun = false; 
     } 
    }); 
    } 

を(autorunned機能へのparam firstRunを渡すために、既存のproposalがあるとして、フラグはもう将来的に必要とされない可能性があることに注意してください)になります。

+0

私は、オートランが観測可能な変更なしにその機能を起動させないようにしたい。 present()は、コンストラクタ呼び出しの終了前に使用できないいくつかのインスタンス変数を使用するためです。 – dagatsoin

+0

自動実行の動作は、依存関係が変更されていなくても一度実行されます。そうじゃない? – dagatsoin

+0

私は初期化を意味します。 – dagatsoin

関連する問題