Sencha Touch里this的用法

时间:2021-04-11 19:00:40

Sencha Touch是js的框架,所以Sencha Touch里this的用法归根结底还是js里this的用法。

只不过在Sencha Touch里很多方法都提供的scope这一参数可以指定方法运行的作用域,

在方法体里也就是指定了this。

在js里this并不是一成不变的,它总是指向调用该方法的对象。

所以,通过改变this,可以起到在改变方法运行的作用域,可以调用更大范围内的函数。

下面的例子是一个form panel,要给form panel里每一个field添加listener.

在addListeners里this指代form panel,

this.getItems();得到每一个item,each遍历每个item,给每一个item的change事件加上

处理函数updateFormRecord,这个函数是在form panel的作用域里面的,

而在each执行的时候,this应该是指向每一个item的,也就是说item并没有updateFormRecord方法,

执行会出问题。

解决办法是each的第二参数允许指定该函数执行的scope,传入this(form panel对象),

所以可以调用到该函数作用域以外的函数。

----------------------------------------------------------------------

Ext.define("MyFormPanel",{

...

...

initialize : function(){
    this.callParent(arguments);
    //add listeners
    this.addListeners();

}

addListeners : function(){

     fieldSetItems = this.getItems();
     fieldSetItems.each(function(itemField) {
          itemField.on('change', this.updateFormRecord, this);
     },this);
}

updateFormRecord : function(field,newValue,oldValue){
    var record = this.getRecord();
    if(record && (newValue!=oldValue)){
    //set value to record
       record.set(field.getName(), newValue);
    }

}

})

----------------------------------------------------------------------

 

---恢复内容结束---