2012-02-11 6 views
1

Applicationと呼ばれる「メイン」オブジェクトがあります。このオブジェクトには、この特定のスクリプトに関連するすべての関数が格納されます。 そのオブジェクトには、子オブジェクトとやりとりするいくつかのさまざまな機能があります(たとえば、start()およびpause())。オブジェクト内の親関数/オブジェクトと正しく対話する方法

これらの関数をApplicationオブジェクトの子オブジェクト(またはそれより深い)から呼び出すときは、Application.function()を直接参照する必要があります。どちらが非常に得ることができるclutty。子のデータと対話する必要がある場合は、これらの関数内で同じケースです。this.Game.instance.sessionIdそれは失敗するようになりました。私の必要性が高まるにつれ、将来さらに多くのオブジェクトを追加するとどうなりますか?他の子/親オブジェクトとやりとりするだけで、時間がかかることはなく、非常に混乱します。

例コード:

var Application = {  
     //Start the whole application 
     start: function() { 
      doSomething(this.Game.instance) //do something with the game instance object 
     }, 

     pause: function() { 
      //pause the current sessionId 
      interactWithMyServer(this.Game.instance.sessionId); //clutty 
     } 

     Game: { 
      //redraw the game to reflect changes 
      redraw: function() { 
      someDrawFunction(this.instance); //draw the instance 
      }, 

      //Stores information about the game instance from the server, changes often 
      //bad example with the pause, but just to get the idea of my example 
      instance: { 
      gameId: 23, 
      sessionId: 32, 
      map: 32, 

      //dummy function 
      pause: function() { 
      Application.pause(); //works, but I have to start with the "root" object, Application - how to avoid this? 
      } 
      } 

     }    
    }; 

言い訳愚かなコードは、ちょうど私の問題を表示しようとしていました。

どう構造これは、というかほとんど適切クリーン方法で、再構築しますか?

答えて

0

説明するように定義されるオブジェクト間には、本質的な永続的な関係はありません。つまり、プロパティ "Game"に対して定義されたオブジェクトは、 "Application"オブジェクトに本質的に関連しておらず、どちらも "Game"に関連するインスタンスではありません。あなたがそれを望むなら、明示的に関連するプロパティを与える必要があります。

var Application = { 
    // ... 
    Game: { 
     //redraw the game to reflect changes 
     redraw: function() { 
     someDrawFunction(this.instance); //draw the instance 
     }, 

     //Stores information about the game instance from the server, changes often 
     //bad example with the pause, but just to get the idea of my example 
     instance: { 
     gameId: 23, 
     sessionId: 32, 
     map: 32, 
     app: null, 

     //dummy function 
     pause: function() { 
      this.app.pause(); //works, but I have to start with the "root" object, Application - how to avoid this? 
     } 
     } 

// ... 

Application.Game.instance.app = Application; 
0

あなたは、いくつかの閉鎖方法を定義することによって、親への参照を渡すことができます

var App= { 


    aplicationFunction: function() { 
     alert("Hello, yes this is application..."); 
    }, 

    app: this, 

    getGameObj: function() { 
     var _that = this; 
     return { 

      that: _that, 

      parentF: function() { 
       this.that.aplicationFunction(); 
      }, 
     }; 
    }, 
}; 

App.getGameObj().parentF(); 

ライブデモ:あなたは一例を、以下のようにそれを使用することができ、より快適さのためにhttp://jsfiddle.net/vZDr2/

gameobj = App.getGameObj(); 
gameobj.parentF(); 
関連する問題