在Extjs中,如何从另一个控制器调用视图中的函数?

时间:2015-08-22 02:40:16

标签: javascript extjs extjs5

我试图让这个在Sencha Fiddle中发挥作用。我面临的问题是我在这一行上收到错误

MyApp.app.getView('MyApp.view.test2').test();

当您在文本框内单击时,它会失败并显示错误(在控制台日志中)未捕获TypeError:MyApp.app.getView(...)。test不是函数

//Controller
Ext.define('MyApp.controller.test', {
    extend: 'Ext.app.ViewController',
    alias: 'controller.test',
    myVar:0,
    init: function() {
    }
});

//View
Ext.define('MyApp.view.test', {
    extend: 'Ext.form.field.Text',
    alias:'widget.test',
    controller: 'test',
    title: 'Hello',   
    listeners: {
        focus: function(comp){
            MyApp.app.getView('MyApp.view.test2').test(); //Fails with an error that test is not a function                        }
    },
    renderTo: Ext.getBody()
});

//View
Ext.define('MyApp.view.test2', {
    extend: 'Ext.form.Panel',
    alias:'widget.test2', 
    title: 'Hello2',     
    renderTo: Ext.getBody(),
    test:function()
    {
        alert('in MyApp.view.test2');
    }
});

Ext.application({
    name: 'MyApp',
    launch: function() {
        Ext.create('MyApp.view.test');
        Ext.create('MyApp.view.test2');
    }
});

1 个答案:

答案 0 :(得分:2)

getView()函数只返回不返回视图实例。见ExtJs 5.1.1 Controller.getView()

  

返回具有给定名称的View类。要创建视图的实例,您可以像使用它来创建视口一样使用它:

     

this.getView('Viewport').create();

要获取创建的视图实例,您可以使用Ext.ComponentQuery将其归档。

//query returns an array of matching components, we choose the one and only
var test2View = Ext.ComponentQuery.query('test2')[0];
// and now we can execute the function
test2View.test();

查看正在运行的简约fiddle

//View
Ext.define('MyApp.view.test', {
    extend: 'Ext.form.field.Text',
    alias: 'widget.test',
    title: 'Hello',
    listeners: {
        focus: function (comp) {
            //query returns an array of matching components, we choose the one and only
            var test2View = Ext.ComponentQuery.query('test2')[0]; 
            test2View.test();
            //MyApp.app.getView('MyApp.view.test2').test();//Fails with an error that test is not a function
        }
    },
    renderTo: Ext.getBody()
});


//View
Ext.define('MyApp.view.test2', {
    extend: 'Ext.form.Panel',
    alias: 'widget.test2',
    title: 'Hello2',
    renderTo: Ext.getBody(),
    test: function ()
    {
        alert('in MyApp.view.test2');
    }
});


Ext.application({
    name: 'MyApp',
    launch: function () {
        Ext.create('MyApp.view.test');
        Ext.create('MyApp.view.test2');
    }
});