javascript - ExtJs5:从 Controller 1 调用 Controller 2 的方法

标签 javascript extjs model-view-controller extjs5

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

正在为每个 View 使用 ViewControllers

问题陈述:现在假设我有两个 VC(Controller1 和 Controller2)。每个都有自己的方法。我想从 Controller1 调用 Controller2 的方法。我想从 Controller1 更新与 Controller2 关联的 View 。

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') 用于获取任何 Controller 的句柄,然后调用其方法。

但是当我使用 ViewController 时,这对我来说不起作用。

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

这是我的代码:

状态栏 View :

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

状态栏 Controller :

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

应用中的一些其他 Controller :

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

最佳答案

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

从一个 ViewController 调用另一个 ViewController 的方法不是一个好的做法,对于大型应用程序,这是通往 hell 的道路,因为它不可避免地导致无法维护 spaghetti code .

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

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

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

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

此外,数据绑定(bind)在很大程度上简化了逻辑,因此不需要那么多 Controller 和监听器。

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

关于javascript - ExtJs5:从 Controller 1 调用 Controller 2 的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24237744/

相关文章:

javascript - Vanilla JavaScript 在主体上设置样式

javascript - 在嵌套对象中查找键并替换其值 - Javascript

extjs - 如何以百分比形式在 Ext.grid.ColumnModel 中设置宽度?

javascript - 最佳NodeJs MVC框架

php - 扩展 Doctrine Entity 以添加业务逻辑

javascript - 使用 JavaScript 获取和设置剪贴板

javascript - 使用Jquery拖放,从拖放的div中获取值

extjs - 我可以使用 ExtJS 表格布局吗?

javascript - SDK 2 : Example of a settings dialog

model-view-controller - 如何使用 URLHelp 模拟静态类中的静态方法? (起订量)