patternfly / patternfly-bootstrap-treeview

Tree View for Twitter Bootstrap -
http://jonmiles.github.io/bootstrap-treeview
Apache License 2.0
200 stars 105 forks source link

Cannot addNode when inside events (due to deep copy) #64

Open vitalyo7 opened 6 years ago

vitalyo7 commented 6 years ago

This example does not work, because node being passed in event is deep copy (and is no longer a part of a tree).

tree.on('nodeSelected', function(event, node, options) {
    tree.addNode([{text: "New"}], tree.getNode(node.nodeId));
});

The node that you get inside the event, cannot be used in addNode operation since the result of which fails to render or make actual changes on the tree.

Locally I have made a work around, that allows you to get the real node using nodeId that you can retrieve from the event.

tree.on('nodeSelected', function(event, node, options) {
    tree.addNode([{text: "New"}], tree.getNode(node.nodeId));
});

Changes in the treeview.js

// Tree manipulation methods
getNode: $.proxy(this.getNode, this),
addNode: $.proxy(this.addNode, this),

...

Tree.prototype.getNode = function (nodeId) {
    return this._nodes[nodeId];
}
vitalyo7 commented 6 years ago

Just realized that there may be a better solution, inside addnode function, it may be best to get parentNode by id that is being passed in node parameter. That way no matter if the node is real or deep-copied, it always gets the version of the node that belongs to the tree.

rogertangcn commented 6 years ago

This is the same issue of #60. I found a way to work around the problem without changing the library. (Same idea as yours but don't have to change the lib. And yeah, it's better to solve the problem at lib level.)

tree.on('nodeSelected', function(event, node, options) {
        var parent = tree.findNodes(node.id, "id");
    tree.addNode([{text: "New"}], parent);
});