In my app, I have 4 buttons and each button represents a different directory. Whenever a button is clicked, I make an Ajax call to build a JStree element and display that directory hierarchy to the user.
Everything works fine, but only for the first button that I click on. Once the JStree element has been built, if I click on another button, the appropriate Ajax calls are performed and the correct responses are received, but the JStree does not update.
I thought perhaps the .html() call was the problem, so I ended up trying .replaceWith() which ended up with the same issue. I also tried chaining .clear().append(), but that too ended up with the exact same issue.
Can anyone point out what I'm doing wrong?
The View
%div
%h3 Nodes
%div
.btn-group{data: {toggle: 'buttons-radio'}}
%div
%button.btn.btn-pill{id: 'abl-test-data-directory-node-1', type: 'button'} Node 1 - loads /home
%div
%button.btn.btn-pill{id: 'abl-test-data-directory-node-2', type: 'button'} Node 2 - loads /boot
%div
%button.btn.btn-pill{id: 'abl-test-data-directory-node-3', type: 'button'} Node 3 - loads /lib
%div
%button.btn.btn-pill{id: 'abl-test-data-directory-node-4', type: 'button'} Node 4 - loads /bin
%div
%h3 Directory
#abl-test-data-directory
The Javascript
$(document).ready(function(){
$('#abl-test-data-directory-node-1').on('click', function() {
buildAblTestDataDirectoryAjaxCall(1);
});
});
$(document).ready(function(){
$('#abl-test-data-directory-node-2').on('click', function() {
buildAblTestDataDirectoryAjaxCall(2);
});
});
$(document).ready(function(){
$('#abl-test-data-directory-node-3').on('click', function() {
buildAblTestDataDirectoryAjaxCall(3);
});
});
$(document).ready(function(){
$('#abl-test-data-directory-node-4').on('click', function() {
buildAblTestDataDirectoryAjaxCall(4);
});
});
function buildAblTestDataDirectoryAjaxCall(nodeIndex){
$.ajax({
method: "GET",
url: "/fire_ajax/" + nodeIndex.toString(),
dataType: "script",
data: nodeIndex,
error: function(xhr, status){
alert('There was a problem');
}
});
};
The Route
get '/fire_ajax/:nodeID', to: 'ajax#build_test_data_explorer'
The Controller Logic
def build_test_data_explorer
@folders = directory_hash(get_node_path())
respond_to do |format|
format.js {render :abl_test_data_explorer}
end
end
def get_node_path
node_id = params[:nodeID]
node_path = ''
case node_id
when "1"
node_path = '/home'
when "2"
node_path = '/boot'
when "3"
node_path = '/lib'
when "4"
node_path = '/bin'
else
node_path = '/home'
end
return node_path
end
The JS.ERB Logic
function build_abl_test_data_JStree(){
$("#abl-test-data-directory").html(function(){
$("#abl-test-data-directory").jstree({
'core' : {
'data' : <%= @folders.to_json.html_safe %>,
'themes' : {
'name' : 'proton'
}
}
});
});
};
build_abl_test_data_JStree();