diff --git a/docs/hexo/source/index.md b/docs/hexo/source/index.md index 537027b..6f212f8 100644 --- a/docs/hexo/source/index.md +++ b/docs/hexo/source/index.md @@ -675,6 +675,41 @@ This method is "syntactic sugar" of `Tree.find(criteria, true)` Remove Node by criteria. +#### [Tree.updateData(criteria, callback)](#Tree-remove-criteria-multiple) + +- **Arguments:** + - `{ Object | String } criteria` (see [find method](#Tree-find-criteria-multiple-false)) + - `{ Function } callback` + +- **Returns:** + - [Selection](#Selection-API) + +- **Usage:** + + This method updates the `data` object in a given node. It is an extension of `find` method but with a slight twist. + The first argument is a criteria while the second is a callback which should return a Node. +```javascript + this.$refs.tree.updateData('Node Text', node => ({ + description: `ID of this node: ${node.id}` + })); +``` + Under the hood, there is also a `forEach` which gives you the ability to do something like this: +```javascript + this.$refs.tree.updateData('Node Text', node => { + if (node.data.someData) { + return { + ...node.data, + isBoolean: true + } + } + + return { + ...node.data, + greeting: 'Hello World' + } + }); +``` + ### Selection API This array-like object has all array methods (forEach, map and so on) because it inherits `Array` object. This collection has very similar behaviour with jQuery. __All actions apply to all items in the collection.__ I'm going to show one example in more details and other methods have similar logic. diff --git a/src/lib/Node.js b/src/lib/Node.js index 00f2d10..c53ff8f 100644 --- a/src/lib/Node.js +++ b/src/lib/Node.js @@ -81,6 +81,14 @@ export default class Node { } } + setData (data) { + this.data = Object.assign({}, this.data, data); + + this.$emit('data:changed', this.data); + + return this.data; + } + state (name, value) { if (undefined === value) { return this.states[name] diff --git a/src/lib/Tree.js b/src/lib/Tree.js index 8a8d974..47b2097 100644 --- a/src/lib/Tree.js +++ b/src/lib/Tree.js @@ -687,6 +687,14 @@ export default class Tree { return new Selection(this, [result[0]]) } + updateData (criteria, callback) { + const nodes = this.find(criteria); + + nodes.forEach(node => node.setData(callback(node))); + + return nodes; + } + getNodeById (id) { let targetNode = null diff --git a/src/mixins/TreeMixin.js b/src/mixins/TreeMixin.js index 5fea97f..4dcac7c 100644 --- a/src/mixins/TreeMixin.js +++ b/src/mixins/TreeMixin.js @@ -186,6 +186,10 @@ export default { return this.tree.expandAll() }, + updateData (criteria, callback) { + return this.tree.updateData(criteria, callback); + }, + collapseAll () { return this.tree.collapseAll() },