2014-06-16 38 views
2

我正在嘗試使用新的ExtJs 5. 我已經根據定義的ExtJs5的MVC模式創建了一個小應用程序。ExtJs5:從控制器1調用控制器2的方法

上午使用ViewControllers每個View

問題陳述:現在假設我有兩個VC(Controller1 & Controller2)。每個人都有自己的方法。我想從Controller1調用Controller2的方法。我想更新Controller1中與Controller2相關的視圖。

E.g. Suppose there is a separate view for Status Bar and a ViewController(StatusBarController). 
This VC has a method to update the view based on whatever message it receives as input parameter. 
All the other controllers in the application will call this VCs method to update the status of the application on the status bar. 

在以前的版本中,this.getController('StatusBarController')被用來獲取句柄到任何控制器,然後調用它的方法。

但是,當我使用ViewController時,這不起作用。

任何人都可以指導我如何實現這件事?而且,無論是做這種事情的正確/理想的方式,還是有更好的選擇?

這裏是我的代碼:

StatusBarView:

Ext.define('MyApp.view.statusbar.StatusBarView', { 
extend : 'Ext.panel.Panel', 
controller: 'StatusBarController', 
region : 'south', 
xtype : 'status-bar-panel', 
html : 'This is a status bar' 
}); 

StatusBarController:

Ext.define('MyApp.controller.StatusBarController', { 
extend : 'Ext.app.ViewController', 
alias: 'controller.StatusBarController', 
updateStatusBar : function(message) { 
    this.getStatusBarView().update(message); 
} 
}); 

在應用一些其他的控制器:

Ext.define('MyApp.controller.ResourcesPanelController', { 
extend : 'Ext.app.ViewController', 
alias : 'controller.ResourcesController', 
onItemClick : function(tree, record, item, index, e, eOpts) { 
      // here I am calling the other controller's method. 
    this.getController('StatusBarController').updateStatusBar(
      record.data.text + ' has been clicked'); 
} 
}); 

回答

8

ViewControllers與他們的意見緊密相關,他們甚至與視圖一起創建和銷燬,他們應該只控制自己的意見。這個想法是在視圖層面將邏輯與UI分開。

從另一個ViewController調用另一個ViewController的方法並不是一個好習慣,對於大型應用程序來說,它是通往地獄的路線,因爲它不可避免地導致無法維護spaghetti code

正確的方法是儘量減少ViewModels,ViewControllers和控制器的數量,讓他們在自己的職責範圍內工作。

例如:假設您想在容器中使用網格和表單。窗體將允許編輯網格中選定的記錄。再加上一些按鈕。這三個視圖(容器,網格和表單)一起組成一個單元。因此:需要

  1. 只有在容器中的一個視圖控制器,所有的觀點可以用它
  2. 需要
  3. 只在容器中的一個視圖模型,所有的觀點可以用它
  4. ,如果你想讓這三人與溝通應用程序的其餘部分的外部世界,容器的視圖控制器可以觸發事件,可以有API方法調用

因此,如果需要的話,你可以有一個MVC(全球)控制器(s)表示,將協調單位的職能,就像我們三人一樣。另外,數據綁定在很大程度上簡化了邏輯,因此控制器和監聽器並不需要那麼多。

請參閱Binding Grid and Form in ExtJS 5示例。

+0

現在,我通過一個全球性的控制器來管理它。 'MyApp.app.getController('StatusBarController')。updateStatusBar()' – DarkKnightFan

0

我的答案是簡單而短: Ext.app.ViewController.fireEvent()

,同時可以與視圖控制器的listeners配置添加任何類型的自定義事件 - 的listen配置狀態「事件域」的文檔,所以我假設兩個控制器都需要駐留在同一個域中,以便能夠以事件方式進行交互。

.fireEvent()的第二個參數可能需要模仿普通觸發事件的元素。

嗯,它也應該能夠訪問它像(在二級控制器):

this.getApplication().getStatusBarController().updateStatusBar('...');