この記事はArchitecting Your App in Ext JS 4, Part 3 | Learn | Senchaの抄訳・意訳です。
Cascading your controller logic on application launch.
Viewのインスタンスを取得するコードはonLaunchメソッドに書くのがいい。onReadyは使わないこと。
onLaunchメソッドは各コントローラに定義でき、すべてのcontroller,model,storeがインスタンス化され、viewがレンダリングされた後で実行される。
onLaunchを使うことでアプリケーション全体のロジックと特定のコントローラのロジックを分けることが出来る。
Step 1
app/controller/Station.js
... onLaunch: function() { // Use the automatically generated getter to get the store var stationsStore = this.getStationsStore(); stationsStore.load({ callback: this.onStationsLoad, scope: this }); } ...
onLaunch内でStoreのロードメソッドを実行するといい。
Step 2
app/controller/Station.js
... onStationsLoad: function() { var stationsList = this.getStationsList(); stationsList.getSelectionModel().select(0); } ...
データがロードされたときに呼び出されるコールバック関数でgetterを使って
StationsListインスタンスを取得している。
最初のitemをセレクトすることでselectionchangeイベントが実行される。
Step 3
app/controller/Station.js
... init: function() { this.control({ 'stationslist': { selectionchange: this.onStationSelect }, ... }); }, onStationSelect: function(selModel, selection) { this.application.fireEvent('stationstart', selection[0]); }, ...
アプリケーションイベントは沢山のコントローラがあり、一つのイベントで実行される関数が各コントローラに散らばっているときに便利。
各コントローラにstationslistのselectionchangeイベントへのリスナを追加する代わりに一つのコントローラがイベントをリスンしてアプリケーションイベントを発火させる。
他のコントローラはアプリケーションイベントへのリスナを登録しておく。
アプリケーションイベントを経由することでViewとコントローラの結合が弱くなる。
アプリケーションイベントはコントローラが全コントローラへのブロードキャスを行うため、他のコントローラの情報がなくてもコントローラ間での通信が出来る。
Step 4
app/controller/Song.js
... refs: [{ ref: 'songInfo', selector: 'songinfo' }, { ref: 'recentlyPlayedScroller', selector: 'recentlyplayedscroller' }], stores: ['RecentSongs'], init: function() { ... // We listen for the application-wide stationstart event this.application.on({ stationstart: this.onStationStart, scope: this }); }, onStationStart: function(station) { var store = this.getRecentSongsStore(); store.load({ callback: this.onRecentSongsLoad, params: { station: station.get('id') }, scope: this }); } ...
initメソッドの中でアプリケーションイベントへのリスナを設定している。