Reputation: 281
jsTree should save the state of the tree on each page redirect / reload, but doesn't do it consistently. the tree seems only save state some of the time.
My tree looks like this, always visible as a navigation menu on the left side of the page:
| Category 1
|
| Category 2
| ---Sub 2.1
|
| Category 3
| --- Sub 3.1
| --- Sub 3.2
| --- Sub 3.2.1
| --- Sub 3.2.2
Let us assume I have selected Category 3.2.2. This redirects the user and correctly highlights the selected category upon page load.
The expectation is that by clicking on Category 1, the user is redirected again and Category 1 is now selected once the page is done loading. This is not what happens. Instead, the user is directed to this page, but Sub 3.2.2 is still shown as selected.
Curiously enough, when I click on Category 3, this category is correctly highlighted; now a different set of nodes do not get selected upon click and redirect.
Here is how the tree is initialized:
$(function() {
// Get categories from JSON server
$.getJSON('/getcategories', function(treedata) {
// Builds JSON data for the tree
var tree = menuRoot(treedata.categoryList);
$('#jsCategoryTree').jstree({
'core' : {'multiple' : false, 'data' : tree},
'state' : { 'key' : 'jsCategoryTree', 'events' : 'activate_node.jstree'},
'plugins' : ['state','cookies','ui','html_data'],
'cookies' : { cookie_options : { path : '/' } }
});
// Binds a link to each node to redirect user
$('#jsCategoryTree').on('activate_node.jstree', function(e, data) {
var categoryId = data.node.id;
location.href = '/?categoryId=' + categoryId;
});
});
})
I have tried to initialize with default events, as well as with various combinations of : changed.jstree, open_node.jstree, close_node.jstree, enable_node.jstree, activate_node.jstree, select_node.jstree, set_state.jstree, refresh.jstree
My understanding is that activate_node.jstree is called every time I click on a node, hence it should fire the save_state method and thus reproduce the correct selection on page reload/redirect.
What could be causing this behaviour?
Upvotes: 2
Views: 2987
Reputation: 281
Solved. The issue was caused by jsTree not being finished with all internal events. Save_state is not called until all events are finished, and the browser was redirecting before save_state was reached, causing unpredictable behaviour.
Using setTimeout to block the browser from redirecting immediately fixed the issue. The value is arbitrary but 100 milliseconds seemed to work for me.
// Binds a link to each node to redirect user
$('#jsCategoryTree').on('activate_node.jstree', function(e, data) {
var categoryId = data.node.id;
setTimeout(function() {location.href = '/?categoryId=' + categoryId;}, 100);
});
Upvotes: 0