Skip to content

Instantly share code, notes, and snippets.

@mikerobi
Created May 9, 2012 20:25
Show Gist options
  • Save mikerobi/2648549 to your computer and use it in GitHub Desktop.
Save mikerobi/2648549 to your computer and use it in GitHub Desktop.
dgrid tree filtering example
new Memory({
data: [
{ id: 0, path: 'a', parentId: null },
{ id: 4, path: 'e', parentId: null },
{ id: 1, path: 'a/b', parentId: 0 },
{ id: 2, path: 'a/c', parentId: 0 },
{ id: 3, path: 'a/c/d', parentId: 2 }
],
mayHaveChildren: function(item) {
return item.hasChildren;
},
getChildren: function(item, options) {
/* get all unfilted children */
var r, results, _i, _len, _results;
results = Memory.prototype.query.call(this, {
parentId: item.id
});
/*
If 3D filtering is turned on, we want the intersection
of the normal query results and everyting in _filtered.
*/
if (this.filter3d) {
_results = [];
for (_i = 0, _len = results.length; _i < _len; _i++) {
r = results[_i];
if (this._filtered[r.id]) _results.push(r);
}
return _results;
} else {
return results;
}
},
query: function(query, options) {
/*
Use the regular query function to get a list
of all matched records. And use it as a stack
*/
var node, parent, roots, stack;
stack = Memory.prototype.query.call(this, query, options);
/*
If filtering is off, we want all matches to be root level,
so return the stack.
*/
if (!this.filter3d) return stack;
/* For any top level nodes in the match hierarchy */
roots = [];
/*
_filtered is used to tell us if a node is a match, or
an ancestor of a match. We need to track this
so we can filter the results in the getChildren function.
*/
this._filtered = {};
while (stack.length) {
node = stack.pop();
/* if the node has already been found skip it */
if (this._filtered[node.id])
continue;
this._filtered[node.id] = true;
/* If the node has a parent, add it to the stack */
parent = this.get(node.parentId);
if (parent) {
stack.push(parent);
} else {
roots.push(node);
}
}
return roots;
}
});
/*
To filter data:
tree.store.filter3d = true
tree.store.set('query', <filter query>)
Unfilter:
tree.store.filter3d = false
tree.store.set('query', <base query>)
Warning, if you do:
tree.store.filter3d = true
tree.store.query(<some query)
The next call to getChildren will return filtered
results, but the tree won't refresh.
I need to update this to support normal queries against the data store
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment