Bind nodes to JS objects

69 views
Skip to first unread message

Sean DeNigris

unread,
Jul 19, 2014, 2:17:44 PM7/19/14
to jst...@googlegroups.com
I asked on StackOverflow :

I want to associate each node in my tree with a domain object. I was passing HTML data and manually storing the domain object in jQuery data:
$('li node description').data('obj', my_domain_object);
However, it seems that jsTree clears that data out during $('#jstree_div').jstree();.
So later, $('li node description').data('obj') is undefined.
What's the best practice to do this with HTML data? Or maybe should I just use JSON data?

Any ideas? 
Thanks. 
Sean DeNigris

Ivan Bozhanov

unread,
Jul 20, 2014, 2:02:21 PM7/20/14
to jst...@googlegroups.com
Use the "data" property on each node if using JSON, or if using HTML - jstree will get the data associated with the node on create, and you can later access it in the "data" property, like so:
on("select_node.jstree", function (e, data) { console.log(data.node.data); }) // you can add and change data using data.node.data.some_key = "some_val"; too

Best regards,
Ivan

Sean DeNigris

unread,
Jul 21, 2014, 2:36:38 PM7/21/14
to jst...@googlegroups.com
On Sunday, July 20, 2014 2:02:21 PM UTC-4, Ivan Bozhanov wrote:
data.node.data.some_key

I was able to access it that way. My understanding now is that, without jsTree, the data is attached to the jQuery HTML node. That is, it can be accessed like "$('li node description').data('some_key')". But jsTree moves this data into the node object returned by the callback, so it must be accessed via "data.node.data.some_key". Does that sound right?

Thanks!

Ivan Bozhanov

unread,
Jul 22, 2014, 12:53:27 AM7/22/14
to jst...@googlegroups.com
Yes, exactly. This is done because of speed. Attaching the data using jQuery's ".data()" every time a node is redrawn proved to be rather slow. Sorry for this inconvenience.

Best regards,
Ivan

Sean DeNigris

unread,
Jul 22, 2014, 10:12:20 AM7/22/14
to jst...@googlegroups.com
On Tuesday, July 22, 2014 12:53:27 AM UTC-4, Ivan Bozhanov wrote:
... Sorry for this inconvenience.

Not at all. I just found it surprising when my data was "gone". It could be a good addition to the docs. I answered and updated the SO question.
Reply all
Reply to author
Forward
0 new messages