如何让我的控制器在 extjs 中调用正确的视图组件?

How can I make my controller call the correct view's component in extjs?

我定义了一个名为 JobListExt.grid.Panel,它有一个带有名为 myButtonitemId 的分机按钮。 JobList 有控制器。在控制器中我有以下代码:

Ext.define('App.controller.JobList', {
  extend: 'Ext.app.Controller',
  refs: [
    {ref: 'jobList', selector: '#jobList'},
    {ref: 'myButton', selector: '#myButton'}
  ],
  init: function(){
    this.control({
      'jobList': {
        select: this.selectJob
      }
    });
  },
  selectJob: function(){
    this.getMyButton().enable();
  }
});

然后我使用 Ext.create 创建了两个 jobList 实例,它们的 ID 分别为 jobList1jobList2。问题是当我 select 在 jobList2 列表中的作业时,它将在 jobList1 而不是 jobList2 上启用 myButton。如何在 jobList 的每个实例上正确启用 myButton

尽量避免通过 itemId 引用,而是使用别名:

// in App.view.JobList.js you should have
Ext.define('App.view.JobList', {
    extend: 'Ext.grid.Panel',
    alias: 'widget.job-list',
    // ...
    dockedItems: [{
        xtype: 'button',
        name: 'myButton',
        text: 'My button',
    }]
});

// and the in the App.controller.JobList.js:
    // ...
    'job-list': {
        selectionchange: function(model, selected) {
            var button = model.view.up('job-list').down('button[name=myButton]');
            button.setDisabled(Ext.isEmpty(selected));
        }
     }

查看示例:https://fiddle.sencha.com/#fiddle/tq1

您使用的是全局控制器,因此它会捕获来自与查询匹配的所有视图的事件。查看 extjs5 中的 MVVM 模式。 Sencha 做得很好,在 MVVM 中每个视图实例都有自己的 ViewController 实例,所以这种情况永远不会发生。如果你想坚持使用 MVC 模式,那么你需要手动控制它。忘掉 refs,如果你有多个视图实例,你就不能使用它们 class。仅通过从当前组件查询获取其他组件。类似于:

Ext.define('App.controller.JobList', {
    extend: 'Ext.app.Controller',

    init: function() {
        this.control({
           'jobList': {
               select: this.selectJob
           }
        });
    },

    selectJob: function(selectionModel){
        //first of all you need to get a grid. We have only selectionModel in this event that linked somehow with our grid
        var grid = selectionModel.view.ownerCt; //or if you find more ellegant way to get a grid from selectionModel, use it
        var button = grid.down('#myButton');
        button.enable();
    }
});