访问在initComponent中声明的变量

3

我需要在sencha中按照mvc模式渲染模板,因此我已经在InitComponent中声明了一些变量,但我无法在init函数以外访问这些变量。我尝试了以下方法:

Ext.define('casta.view.Intro', {
    extend: 'Ext.tab.Panel',
    //alias: 'widget.currentDate', //this makes it xtype 'currentDate'
    //store: 'CurrentDateStore',


    initComponent: function(){
        this.planetEarth = { name: "Earth", mass: 1.00 };

        this.tpl = new Ext.Template(['<tpl for".">', '<p> {name} </p>', '</tpl>'].join(''));
        this.tpl.compile();
        this.callParent(arguments);

    },
    html:this.tpl.apply(this.planetEarth)
});

错误

this.tpl is undefined
[Break On This Error]   

html:this.tpl.apply(planetEarth)
1个回答

1

我非常确定 JavaScript 的作用域并不是这样的...

在你的例子中,有两种方法可以实现你想要做的事情:

//this is the bad way imo, since its not really properly scoped.
// you are declaring the planeEarth and tpl globally
// ( or wherever the scope of your define is. )
var plantetEarth = { name: "Earth", mass: 1.00 }
var tpl = new Ext.Template(['<tpl for".">', '<p> {name} </p>', '</tpl>'].join(''));
tpl.compile();
Ext.define('casta.view.Intro', {
    extend: 'Ext.tab.Panel',
    //alias: 'widget.currentDate', //this makes it xtype 'currentDate'
    //store: 'CurrentDateStore',


    initComponent: function(){

        this.callParent(arguments);

    },
    html:tpl.apply(planetEarth)
});

或者

//I would do some variation of this personally.
//It's nice and neat, everything is scoped properly, etc etc
Ext.define('casta.view.Intro', {
    extend: 'Ext.tab.Panel',
    //alias: 'widget.currentDate', //this makes it xtype 'currentDate'
    //store: 'CurrentDateStore',


    initComponent: function(){

        this.tpl = new Ext.Template(['<tpl for".">', '<p> {name} </p>', '</tpl>'].join(''));
        this.tpl.compile();
        this.tpl.apply(this.planetEarth);
        this.html = this.tpl.apply(this.planetEarth)
        this.callParent(arguments);

    },

});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接