首先我们要了解change事件工作原理:
其实change事件是在blur事件的方法中触发的,看看这段注释:
/**
* @event change
* Fires just before the field blurs if the field value has changed
* @param {Ext.form.Field} this
* @param {Mixed} value The changed value
* @param {Mixed} value The original value
*/
不难看出如果控件的值改变时会在blur事件前触发change事件
找到ext的ext-all.js找到Ext.form.Field控件的定义里的blur事件源码:
onBlur : function() {
this.beforeBlur();
if (this.focusClass) {
this.el.removeClass(this.focusClass)
}
this.hasFocus = false;
if (this.validationEvent !== false && (this.validateOnBlur || this.validationEvent == "blur")) {
this.validate()
}
var a = this.getValue();
if (String(a) !== String(this.startValue)) {
this.fireEvent("change", this, a, this.startValue)
}
this.fireEvent("blur", this);
this.postBlur()
},
下面代码为触发change事件部分:
var a = this.getValue();
if (String(a) !== String(this.startValue)) {
this.fireEvent("change", this, a, this.startValue)
}
如下为回车事件激活chang事件后再失去焦点是就会再次触发change事件错误代码:
field.on("specialKey" , function(f, e) {
if (e.getKey() == Ext.EventObject.ENTER) {//响应回车
field.fireEvent('change');
}
});
这里没有改变控件的 startValue 而是为undefined 所以 还会触发change事件
那么个人修改意见,回车事件时修改该控件的startValue值为当前值就不会再触发change事件了
两种不同方法:
//方法1.加在控件的listener配置中
specialkey : function(field, e) {
if (e.getKey() == Ext.EventObject.ENTER) {
var a = this.getValue();
if (a != '') {
this.fireEvent("change", this, a, this.startValue)
}
this.startValue = this.getValue();
}
}
//方法2.定义在控件加载完成后js中
if (Ext.isDefined(field)) {
field.on("specialKey" , function(f, e) {
if (e.getKey() == Ext.EventObject.ENTER) {//响应回车
var a = field.getValue();
if (a != '') {
field.fireEvent("change", field, a, field.startValue)
}
field.startValue = field.getValue();
}
});
};
改了startValue就不会重复触发change事件了。