In jsTree , How to get Node information by node id? - javascript

In jsTree ,How to get Node information by node id ?
I know id of following node i.e 295 then how to get complete node information
<item id="295" parent_id="192" title="itemTitle" version="1">
<content><name>Bhushan Sambhus</name></content>
</item>
above xml part rendered into jsTree is as follows
$("#treeViewDiv").jstree({
"xml_data" : {
"data" : "" +
"<root>" +
"<item id="295" parent_id="192" title="itemTitle" version="1">"+
"<content><name>Bhushan Sambhus</name></content> "+
"</item>"
}
"plugins" : [ "themes", "xml_data","ui" ]
});
Something like following psudo code
function getNodeByNodeID(node_id){
// some code
// $.jstree.get_node ...... etc ?
//
return relatedNodeInformation;
}
var nodeInfo = getNodeByNodeID(providedNodeID) // psudo code
// any api in jstree to get nodeInfo by providedNodeID?
var parent_id_value = nodInfo.attr("parent_id");
var title_value = nodInfo.attr("title");
var version_value = nodInfo.attr("version");
var node_name = nodInfo.children("a").text()
alert(parent_id_value+" :: "+title_value+" :: "+version_value+" :: "+node_name);
Input : 295
Output: 192 :: node_name :: 1 :: node_name
Any help or guidance in this matter would be appreciated

If I'm understanding your question correctly, you can accomplish what you want to do like this:
var nodInfo = $("#" + providedNodeId);
var parent_id_value = nodInfo.attr("parent_id");
var title_value = nodInfo.attr("title");
var version_value = nodInfo.attr("version");
var node_name = nodInfo.children("a").text();
alert(parent_id_value+" :: "+title_value+" :: "+version_value+" :: "+node_name);

Just want to help keep the answer up-to-date. Using jstree 3.1.0, node objects (not DOM objects) are fetched by using this code:
var treeMain; // reference holder
$(document).ready( function () { // when the DOM is ready
treeMain = $('#treeMenus').jstree(); // create the tree and get the reference
});
function getNode( sNodeID)
{
return $.jstree.reference(treeMain).get_node(sNodeID); // use the tree reference to fetch a node
}
I've seen several answers to this question on StackOverflow that all talk about getting back to the DOM object of a tree item. I'm willing to bet that most people asking this question really want to get back to the underlying JSON data object of a tree item, which is why they say they want the node object (which has the .original property). Specifically, you need this for implementing things like "create" functionality where you need to create a new JSON data object with a ParentID that is set to the ID of the parent JSON data object. I searched for 2 days and didn't find anything clear in the jstree documentation that explained this:
$.jstree.reference(treeMain).get_node(sNodeID);
simple call. In their defense, they do have a 1 line example buried in here:
http://www.jstree.com/docs/interaction/
but it's an example most people won't care about (the user will be selecting nodes most of the time), and certainly not clear for what it is actually capable of doing. Anyways... hope this is helps save someone else a couple of days. =)

Related

Creating .json file and storing data in javascript -- using vis.js

In my project I need to save the data to .txt or .xml or .json file. I could not find any answer from vis.js website/issues blog. It might be simple, do not know. Really helpful if anyone help me out with example code. Thank you so much in advance.
function saveData(data,callback) {
data.id = document.getElementById('node-id').value;
data.label = document.getElementById('node-label').value;
clearPopUp();
callback(data);
}
If I understand you correctly, you are looking for a way to save data and options of a graph. In my graph editor adaptation for TiddlyWiki Classic I use the following method to extract data (the full implementation can be found in the repo, see config.macros.graph.saveDataAndOptions, here's a simplified one):
config.macros.graph.saveDataAndOptions = function(network,newOptions) {
newOptions = newOptions || {};
// get nodes and edges
var nodes = network.body.data.nodes._data; // contains id, label, x,y, custom per-node options and doesn't contain options from options.nodes; presumably contains option values set when network was created, not current ones (it is so for x,y)
// no suitable getter unfortunately
var edges = network.body.data.edges._data; // map; for edges to/from? certain node use network.getConnectedNodes(id)
// network.body.data.edges._data is a hash of { id: , from: , to: }
// get node positions, options
var positions = network.getPositions(), // map
options = // get options stored previously
// merge newOptions into options
for(var nodeId in nodes) {
// nodes[nodeId].x is the initial value, positions[nodeId].x is the current one
if(positions[nodeId]) { // undefined for hidden
nodes[nodeId].x = positions[nodeId].x;
nodes[nodeId].y = positions[nodeId].y;
}
storedNode = copyObjectProperties(nodes[nodeId]);
storedNodes.push(storedNode);
}
//# do whatever you need with storedNodes, edges and options
// (pack them with JSON.stringify, store to a file etc)
};
However, while this works ok for storing data, this only helps to save options passed for storing explicitly which can be not very nice for some cases. I use this method in manipulation helpers and on dragEnd (network.on("dragEnd",this.saveToTiddlerAfterDragging), config.macros.graph.saveToTiddlerAfterDragging = function(stuff) { config.macros.graph.saveDataAndOptions(this,{ physics: false }); };). I haven't recieved any better suggestions, though.
If you need to get data and options reactively and setting such helper to handle certain edit events can't solve your problem, then I suggest wrapping nodes, edges and options as vis.DataSet and save those when needed. This is related too.
To answer the question about events/other ways to use such methods. Here's how I use them:
I save data after drag&drop moving of nodes, this is done using an event handler. Namely, I introduced
config.macros.graph.saveToTiddlerAfterDragging = function(stuff) {
config.macros.graph.saveDataAndOptions(this,{ physics: false });
};
(when drag&drop is used, physics should be switched off, otherwise coordinates won't be preserved anyway) and then I use
network.on("dragEnd",this.saveToTiddlerAfterDragging);
so that changes are saved.
As for saving after adding/editing a node/edge, I apply saving not by an event (although it's nice thinking, and you should try events of DataSet, since there's no special graph events for that). What I do is I add an elaborated hijack to the manipulation methods. Take a look at the source I've linked after the
var mSettings = options.manipulation;
line: for each manipulation method, like options.manipulation.addNode I hijack it so that its callback is hijacked to call config.macros.graph.saveDataAndOptions in the end. Here's a simplified version of what I'm doing:
var nonSaving_addNode = options.manipulation.addNode;
options.manipulation.addNode = function(data,callback) {
// hijack callback to add saving
arguments[1] = function() {
callback.apply(this,arguments); // preserve initial action
config.macros.graph.saveDataAndOptions(network); // add saving
};
nonSaving_addNode.apply(this,arguments);
}
The thing is, addNode is actually called when the add node button is clicked; though, I'm using a customized one to create a popup and apply changes once user is happy with the label they chose.

jsTree can't find node by ID

I have no trouble getting the jsTree to implement on the page.
I tried SO MANY different things from so many suggestions on various sites.
$('#myTree').jstree({
....
})
.on('loaded.jstree', function (e, dta) {
var t = $('#myTree').jstree(true);
var n = t.get_node("myIDstring");
console.log(t);
console.log(n);
});
My last attempt before this post was to try using the .on(loaded.jstree) callback as shown above. But it didn't make any difference from where I tried to get the node. Always the same result.
console.log(t) proves I have a tree. In this case I see I have a cnt of children = 217.
"myIDstring" is cut-and-pasted from the id attribute of one of the nodes I drilled down on in the javascript console of the console.log(t) echo.
console.log(n); only echos 'false'.
If I try t.find() I get find() is not a function error in the console.
van n = $('#myTree').jstree(true).get_node("myIDstring");
fails just the same as var n = t.get_node();
Thanks.
PS: Yes. I know I could just as well us the value of dta. But my goal is to not use this code from inside the .no('loaded.jstree')
The loaded.jstree is fired when you just have the root node loaded. Better use ready.jstree event like below. Also check demo - Fiddle Demo
$('#myTree')
.jstree({
...
})
.on('ready.jstree', function(){
var t = $('#myTree').jstree(true);
var n = t.get_node("myIDstring");
console.log(t);
console.log(n);
}

ngjstree: error when select node automatically

I'm using NgJsTree (https://github.com/ezraroi/ngJsTree) for create a tree. I would like that the option choose by user was saved; so I'm saving the user's choice and the full path in a pair of variable. In particular case, I get the full path like this data.instance.get_path(data.node,'/'); and the selected node in this way data.instance.get_node(data.selected[i])
I trigger the loaded event with this function:
openSelectedNode = function(e, data){
var nodes = config.path.split("/");
for(var i=0;i<nodes.length;i++){
$(this).jstree("open_node", $('#' + nodes[i].replace(" ", "")));
}
$(this).jstree('select_node', $('#' + nodes[nodes.length-1] ));
}
So in this way, when the tree is load, I can reopen the tree and select the correct node. The code works, but in console I have this error:
Uncaught TypeError: Cannot read property 'parents' of undefined
It isn't the right approach? Am i doing any errors?
Thanks in advance.
Regards
It looks like you might be calling node.parents somewhere, which happened to me. Also, I would approach your problem different.
I would:
Use the instance provided by ngJStree to reference the tree, and then use
var selectedNode = vm.treeInstance.jstree(true).get_selected();
Store that nodes id, then set its state to "selected: true" before you create the the tree the next time. It should be already selected that way.

Display neo4j node properties with Sigma.js

I am using Sigma.js with the cypher plugin to visualise my neo4j database. After following the simple example here https://github.com/jacomyal/sigma.js/blob/master/examples/load-neo4j-cypher-query.html , it is working well. I edited the plugin so that the graph labels displayed are the names of my neo4j nodes, however I would also like to show the other node properties when clicking on the label or node.I am quite new to JavaScript so would like to know if this is possible for a beginner like me to do and if it is where is the best place for me to start.
You have to register an event on the click or hover node.
There is an example into sigmajs for event : https://github.com/jacomyal/sigma.js/blob/master/examples/events.html
This is a short code that demonstrate how to make this. Replace the alert method by what you want.
sigma.bind('overNode', function(event) {
alert(event.data.node);
});
If you just want to discover your database, take a look at tank-browser : https://www.npmjs.com/package/tank-browser
Cheers
You have to edit Cypher plugin
First: Define var let's assume we will call it "has" at the beginning of the file.
Second: You should add ul in your html and add class to it called 'popover'
Third: Add to cypherCallback method you should add inside else if (typeof sig === 'object')
sig.graph.read(graph);
sig.bind('clickNode', function(e) {
var clicknode = e.data.node;
// empty the printed list
$('.popover').empty();
has='';
// create the tlis tof prop. from returend Object
for(var keys in clicknode.neo4j_data ){
$('.popover').append(' <li>' + keys + ' = '+ clicknode.neo4j_data[keys] + '</li>');
has+= 'n.' +keys + '="'+ clicknode.neo4j_data[keys] + '"AND ';
}
$('.popover').show();
});
sig.bind('clickStage', function(e) {
$('.popover').hide();
});

How to alter DOM with xmldom by XPath in node.js?

I am trying to alter a DOM structure in node.js. I can load the XML string and alter it with the native methods in xmldom (https://github.com/jindw/xmldom), but when I load XPath (https://github.com/goto100/xpath) and try to alter the DOM via that selector, it does not work.
Is there another way to do this out there? The requirements are:
Must work both in the browser and server side (pure js?)
Cannot use eval or other code execution stuff (for security)
Example code to show how I am trying today below, maybe I simply miss something basic?
var xpath = require('xpath'),
dom = require('xmldom').DOMParser;
var xml = '<!DOCTYPE html><html><head><title>blah</title></head><body id="test">blubb</body></html>';
var doc = new dom().parseFromString(xml);
var bodyByXpath = xpath.select('//*[#id = "test"]', doc);
var bodyById = doc.getElementById('test');
var h1 = doc.createElement('h1').appendChild(doc.createTextNode('title'));
// Works fine :)
bodyById.appendChild(h1);
// Does not work :(
bodyByXpath.appendChild(h1);
console.log(doc.toString());
bodyByXpath is not a single node. The fourth parameter to select, if true, will tell it to only return the first node; otherwise, it's a list.
As aredridel states, .select() will return an array by default when you are selecting nodes. So you would need to obtain your node from that array.
You can also use .select1() if you only want to select a single node:
var bodyByXpath = xpath.select1('//*[#id = "test"]', doc);

Categories