昨天tree的搜索,弄了很久,终于弄出来了。
首先写一个类。这是一个工具类
Ext.define("Sharera.util.TreeFilter",{
filterByText: function(text,by) {
this.filterBy(text, by);
},
/**
* Filter the tree on a string, hiding all nodes expect those which match and their parents.
* @param The term to filter on.
* @param The field to filter on (i.e. 'text').
*/
filterBy: function(text, by) {
this.clearFilter();
var view = this.getView(),
me = this,
nodesAndParents = [];
// Find the nodes which match the search term, expand them.
// Then add them and their parents to nodesAndParents.
this.getRootNode().cascadeBy(function(tree, view){
var currNode = this;
if(currNode && currNode.data[by] && currNode.data[by].toString().toLowerCase().indexOf(text.toLowerCase()) > -1) {
me.expandPath(currNode.getPath());
while(currNode.parentNode) {
nodesAndParents.push(currNode.id);
currNode = currNode.parentNode;
}
}
}, null, [me, view]);
// Hide all of the nodes which aren't in nodesAndParents
this.getRootNode().cascadeBy(function(tree, view){
var uiNode = view.getNodeByRecord(this);
if(uiNode && !Ext.Array.contains(nodesAndParents, this.id)) {
Ext.get(uiNode).setDisplayed('none');
}
}, null, [me, view]);
},
clearFilter: function() {
var view = this.getView();
this.getRootNode().cascadeBy(function(tree, view){
var uiNode = view.getNodeByRecord(this);
if(uiNode) {
Ext.get(uiNode).setDisplayed('table-row');
}
}, null, [this, view]);
}
});
接来下在所需要用到的tree面板中使用:
Ext.define('Sharera.view.user.system.directory.UserUnitTree', {
extend: 'Ext.tree.Panel',
alias : 'widget.directory.userunittree',
mixins: {
treeFilter: 'Sharera.util.TreeFilter'
}
同时添加一个trigger组件。
tbar:[{
xtype: 'trigger',
triggerCls: 'x-form-clear-trigger',
onTriggerClick: function () {
this.setValue('');
var panel=this.ownerCt.ownerCt;
panel.clearFilter();
},
width:'100%',
emptyText:'请输入用户名',
enableKeyEvents: true,
listeners: {
keyup: {
fn: function (field, e) {
var panel=this.ownerCt.ownerCt;
if (Ext.EventObject.ESC == e.getKey()) {
field.onTriggerClick();
} else {
panel.filterByText(this.getRawValue(),'fullname');
}
}
}
}
}],
注意:如果我们要搜索的是name,那么filterByText方法的第二个参数就是name,我这里用fullname。
这样就可以了,我的效果图如下: