subscribe(id, callback, [ignoreChildren])
Assigns a callback function to a node. The callback function is triggered when the node or its child nodes get updated.
Parameters
- id (string) - string id of a node.
- callback (function) - function to be triggered when the node or its child nodes get updated. Two arguments,
data
andnode
, will be passed to the function. - ignoreChildren (boolean, optional) - option to ignore children. If set to
true
, updates of child nodes won't trigger the callback function. Default isfalse
.
Returns
- (function) - Unsubscribe function that removes the assigned callback function from the node.
Examples
import Treeful from 'treeful';
Treeful.add('n1', 1);
let unsubscribe = Treeful.subscribe('n1', callback);
// When node 'n1' updates, all callback functions subscribed to node 'n1' will be triggered
// unsubscribe() may be called to unsubscribe callback from node 'n1'
function callback(data, node) {
document.getElementById('data').innerHTML = data;
}
Tip 1: Make full use of tree structure. Create callback functions that would subscribe to multiple nodes.
import Treeful from 'treeful';
Treeful.add('n1', 1);
.add('n2', 2, 'ㅜn1');
let unsubscribe = Treeful.subscribe('n1', callback);
// callback will be triggered when either node 'n1' or 'n2' updates
function callback(data, node) {
document.getElementById(node).innerHTML = data;
}
Tip 2: In React, callback function can be used to update the component's states.
import React, { Component } from 'react';
import Treeful from 'treeful';
class MyPage extends Component {
constructor(props) {
Treeful.add('my-component')
.add('isLoaded', false, 'my-component')
.add('count', 0, 'my-component');
}
render() {
return (
<MyComponent></MyComponent>
);
}
}
class MyComponent extends Component {
constructor(props) {
super(props);
this.state = {
isLoaded: Treeful.get('isLoaded'),
count: Treeful.get('count')
};
}
componentDidMount() {
this.unsubscribe = Treeful.subscribe('my-component', this.callback.bind(this));
}
componentWillUnmount() {
this.unsubscribe();
}
callback(data, node) {
const state = {};
state[node] = data;
this.setState(state);
}
render() {
return (
<div>
<p>isLoaded: {this.state.isLoaded}</p>
<p>count: {this.state.count}</p>
</div>
);
}
}