使用Ext中的Checkbox时,经常需要随form一起提交,但Checkbox设置的默认的提交值为"on"或"",后台代码中需要对字段的提交进行判断后取值,不符合我们通常的使用习惯,即直接将提交的值转换为对应的boolean类型,为此,特进行扩展和封装,以满足通过的使用方式,代码如下:
justgin.bap.CheckboxEx = Ext.extend(Ext.form.Checkbox, {
trueValue: true,
falseValue: false,
hiddenField: {value:''},
onRender : function(ct, position){
justgin.bap.CheckboxEx.superclass.onRender.call(this, ct, position);
var hidden = this.el.insertSibling({tag:'input', type:'hidden', name: this.name}, 'before', true);
hidden.value = this.hiddenField.value;
this.hiddenField = hidden;
this.el.dom.removeAttribute('name');
this.on('check', this.onCheck);
},
setValue : function(v){
var me = this;
justgin.bap.CheckboxEx.superclass.setValue.call(this, v);
this.hiddenField.value = this.checked?me.trueValue:me.falseValue;
},
getValue : function(v){
return this.hiddenField.value;
},
onDestroy : function(){
Ext.destroy(this.wrap);
justgin.bap.CheckboxEx.superclass.onDestroy.call(this);
},
onCheck : function(me, checked){
this.hiddenField.value = checked?me.trueValue:me.falseValue;
}
});
- 扩展两个属性trueValue和falseValue,可提供使用者指定选中或取消时提交的值,默认为true和false。
- 重写字段的onRender方法,在render时,移除用来展示的html的input元素的名称,插入一个的同名hidden元素,保存要提交的值,不改变使用方式的前提下,能保证from在提交时,将插入的新元素提交,确保了设置的值会提交到后台。
- 重写setValue和getValue方法,保证了存取值时数据的同步。
- 常用的Ext创建对象的方式有两种:new justgin.bap.CheckboxEx()和Ext.create({xtype: 'checkbox'}),要想使用户在使用第二种方式时创建一个自己扩展的对象,可以在类的声明后加入一句对象类型的注册语句即可
Ext.reg('checkbox', justgin.bap.CheckboxEx);