【问题标题】:ExtJs5: Call Controller 2's method from Controller 1ExtJs5:从控制器 1 调用控制器 2 的方法
【发布时间】:2014-08-05 22:15:02
【问题描述】:

我正在尝试新的 ExtJs 5。 我根据 ExtJs5 定义的 MVC 模式创建了一个小应用程序。

我为每个View 使用ViewControllers

问题陈述:现在假设我有两个 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 时,这在我的情况下不起作用。

谁能指导我如何实现这个目标?还有这是否是做这件事的正确/理想方式还是有更好的选择?

这是我的代码:

状态栏视图:

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');
}
});

【问题讨论】:

    标签: javascript extjs model-view-controller extjs5


    【解决方案1】:

    ViewController 与其视图密切相关,它们甚至与视图一起创建和销毁,它们应该只控制自己的视图。这个想法是在视图级别将逻辑与 UI 分开。

    从另一个 ViewController 调用方法不是一个好习惯,而且对于大型应用程序来说,这是通往地狱的道路,因为它不可避免地会导致无法维护spaghetti code

    正确的做法是尽量减少 ViewModel、ViewController 和 Controller 的数量,让它们在各自的职责范围内工作。

    例如:假设您想要一个网格和一个容器中的表单。表单将允许编辑在网格中选择的记录。加上一些按钮。这三个视图(容器、网格和表单)共同构成一个单元。因此:

    1. 容器只需要一个ViewController,所有视图都可以使用
    2. 容器中只需要一个ViewModel,所有视图都可以使用
    3. 如果您想让这三者与应用程序其余部分的外部世界进行通信,容器的视图控制器可以触发事件并可以有 API 方法来调用

    因此,如果需要,您可以拥有一个 MVC(全局)控制器来协调单元的功能,就像我们的三重奏一样。

    此外,数据绑定在很大程度上简化了逻辑,因此不需要那么多控制器和侦听器。

    参见Binding Grid and Form in ExtJS 5 示例。

    【讨论】:

    • 目前,我使用全局控制器来管理它。 MyApp.app.getController('StatusBarController').updateStatusBar()
    【解决方案2】:

    我的回答很简单: Ext.app.ViewController.fireEvent()

    虽然可以使用 ViewController 的 listeners 配置添加任何类型的自定义事件 - listen 配置的文档状态为“事件域”,所以我假设两个控制器都需要驻留在相同的域,以便能够按事件进行交互。

    .fireEvent() 的第二个参数可能需要模仿普通触发事件的元素。

    嗯,也应该可以这样访问它(在辅助控制器中):

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-30
      • 2016-11-28
      • 1970-01-01
      • 2014-09-08
      • 1970-01-01
      • 2022-11-01
      相关资源
      最近更新 更多