前几天研究了combobox-tree,把自己一点心得发出来
自己定义一个combobox
Ext.ux.form.TreeComboBox = Ext.extend(Ext.form.ComboBox, {
initComponent : function(ct, position) {
this.divId = 'tree-' + Ext.id();
if (isNaN(this.maxHeight))
this.maxHeight = 200;
Ext.apply(this, {
tpl : '<tpl>' + '<div style="height:' + this.maxHeight + 'px;">' + '<div id="' + this.divId + '"></div>' + '</div></tpl>'
});
//tree的节点
var root = new Ext.tree.AsyncTreeNode({
text : this.rootText,
id : this.rootId,
draggable : false,
autoHeight : true,
autoScroll : true,
//这里注意下,我的数据是下面setData的,加载页面就传进来了
// loader : new Ext.tree.TreeLoader({
// dataUrl : this.treeUrl,
// clearOnLoad : true
// })
});
//一个tree
this.tree = new Ext.tree.TreePanel({
border : false,
root : root,
rootVisible : this.rootVisible,
listeners : {
scope : this,
click : function(node) {
this.setValue(node);
this.collapse();
}
}
});
//加载数据
root.setData(initData.goodTreeData);
//判断选择的是否是节点
this.tree.on('click',this.onViewClick,this);
//继承父类的构造函数
Ext.ux.form.TreeComboBox.superclass.initComponent.call(this);
},
onRender : function(ct, position) {
//继承父类的Onrender展开
Ext.ux.form.TreeComboBox.superclass.onRender.call(this, ct, position);
//默认展开
this.on("expand", function() {
if (!this.tree.rendered) {
this.tree.render(this.divId);
this.tree.expandAll();
}
}, this)
},
onViewClick : function(doFocus){
if(doFocus !== false){
this.el.focus();
}
}
});
Ext.reg('uxtreecombobox', Ext.ux.form.TreeComboBox);
//重新定下下setValue方法
Ext.override(Ext.form.ComboBox, {
setValue : function(node) {
if (typeof node == "object") {
// 当node为object对象时 node和tree里面的对应
this.lastSelectionText = node.text;
// 设置显示文本为node的text
this.setRawValue(node.text);
if (this.hiddenField) {
// 设置隐藏值为node的id
this.hiddenField.value = node.id;
}
this.value = node.id;
return this;
} else {
// 当node为文本时
var text = node;
if (this.valueField) {
var r = this.findRecord(this.valueField, node);
if (r) {
text = r.data[this.displayField];
} else if (Ext.isDefined(this.valueNotFoundText)) {
text = this.valueNotFoundText;
}
}
this.lastSelectionText = text;
if (this.hiddenField) {
this.hiddenField.value = node;
}
Ext.form.ComboBox.superclass.setValue.call(this, text);
this.value = node;
return this;
}
}
});
js代码
xtype : 'uxtreecombobox',
id : 'lgtid',
hiddenName : 'name',
editable : false,
store : lgtidStore,
shadow : true,
mode : 'local',
displayField : 'name',
valueField : 'lgtid',
triggerAction : 'all',
allowBlank : false,
forceSelection : true,
maxHeight : 150,
autoHeight : true,
listeners : {
specialkey : function(field, e) {
if (e.getKey() == Ext.EventObject.ENTER) {
reloadDepotInDs()
}
}
}