Programatically expanding nodes in jstree with ajax load - jstree

I have a tree made with jstree which loads partially and loads on via json_data plugin as you expand nodes. Here's the crux of the code:
$("#TreeViewDiv")
.jstree(
{
json_data:
{
ajax:
{
url: "/Website/GetNodes",
data: function (node) {
//do some stuff to compile data for backend here
return {
//insert data for backend here
};
},
error: function () {
$("#TreeViewDiv").html("Error initializing tree");
}
}
},
plugins: ["json_data", "ui"]
});
I then want to expand some of the nodes and select a leaf node, depending on which user is accessing the site. I do this in a loop as follows:
var nodeValues = [Parent, firstChild, leaf];
for (var j = 0; j < nodeValues .length-1; j++) {
$("#TreeViewDiv").jstree("open_node", $("input[value='" + nodeValues [j] + "']"));
}
Opening the Parent node works fine and the firstChild is exposed when the tree is shown but the firstChild node is not open. If I kick off the loop again, the firstchild opens successfully to show the leaf node.
My guess is that the request hasn't completed and the firstChild tree node doesn't exist when the above loop tries to open it. Is there a way to wait for the nodes to load before trying to open the next node? Thank you!

Ok, so I figured it out eventually. Here's a way to do it with deferreds. There's probably a neater way but my head hurts after a day of playing with this so refactoring will have to wait :)
var deffereds = $.Deferred(function (def) { def.resolve(); });
var nodeValues = [Parent, firstChild, leaf];
for (var j = 0; j < nodeValues .length-1; j++) {
deffereds = (function(name, deferreds) {
return deferreds.pipe(function () {
return $.Deferred(function(def) {
$("#TreeViewDiv").jstree("open_node", $("input[value='" + name + "']"), function () {
def.resolve();
});
});
});
})(nodeValues [j], deffereds);
}
This basically places the call to open_node in a deferred and uses the callback from the open_node functions to resolve the deferred thus ensuring that no node is opened before its parent has been opened.

Related

Automatically load node children in fancytree

I have a fancytree implementation where each parent node has a child node that can be selected. After a user selects specific children, she is able to save her selections and settings so that she can come back to it later.
I'm able to do all of this, except for when I do an initial load of previously saved data. What I need to do is identify the nodes that need to be opened (and its children selected), and have Fancytree open those nodes and select the children.
I'm using lazy loading, and when the lazyloading event fires I'm able to check to see if the child needs to be selected and do so as needed. What I'd like to be able to do is programmatically do the same thing so that all the previously selected children are loaded and selected upon load. Currently, I'm attempting this in this way:
function getMultipleFieldsNoReset(element,selectedFieldsArray) {
var fieldCreator = element.value;
var tree = $("#multipleFields").fancytree("getTree");
var treeOptions = {
url: "urltogetdata",
type: "POST",
data: {
id: fieldCreator
},
dataType: "json"
};
tree.reload(treeOptions);
for (var i = 0, len = selectedFieldsArray.length; i < len; i++) {
var valueAry = selectedFieldsArray[i].split("-");
var growerNode = valueAry[0];
var farmNode = valueAry[1];
var fieldNode = valueAry[2];
var node = tree.getNodeByKey(growerNode);
console.log(node);
}
}
My problem is that tree.getNodeByKey(growerNode) never finds the node, even though I'm able to find the node in the console after this runs. It seems like the parent nodes aren't loaded yet, which can cause this issue, but I'm not certain where I can set a complete function. Where can I do this? Or even better, is there a cleaner way to handle this?
The OP / Fletchius has got solution on this issue and below is the answer of it. I achieved it in some different way but event loadChildren is the same. from which we both found solution. Just I'm loading those nodes which are selected nodes and lazy true meaning there are children down after this node. And only lazy=true can be useful for this.load(); explicit event.
loadChildren:function(event, data){
var node = data.node;
$(node.children).each(function(){
if(this.selected && this.lazy)
{
this.load();
}
});
},

RxJs Observable with infinite scroll OR how to combine Observables

I have a table which uses infinite scroll to load more results and append them, when the user reaches the bottom of the page.
At the moment I have the following code:
var currentPage = 0;
var tableContent = Rx.Observable.empty();
function getHTTPDataPageObservable(pageNumber) {
return Rx.Observable.fromPromise($http(...));
}
function init() {
reset();
}
function reset() {
currentPage = 0;
tableContent = Rx.Observable.empty();
appendNextPage();
}
function appendNextPage() {
if(currentPage == 0) {
tableContent = getHTTPDataPageObservable(++currentPage)
.map(function(page) { return page.content; });
} else {
tableContent = tableContent.combineLatest(
getHTTPDataPageObservable(++currentPage)
.map(function(page) { return page.content; }),
function(o1, o2) {
return o1.concat(o2);
}
)
}
}
There's one major problem:
Everytime appendNextPage is called, I get a completely new Observable which then triggers all prior HTTP calls again and again.
A minor problem is, that this code is ugly and it looks like it's too much for such a simple use case.
Questions:
How to solve this problem in a nice way?
Is is possible to combine those Observables in a different way, without triggering the whole stack again and again?
You didn't include it but I'll assume that you have some way of detecting when the user reaches the bottom of the page. An event that you can use to trigger new loads. For the sake of this answer I'll say that you have defined it somewhere as:
const nextPage = fromEvent(page, 'nextpage');
What you really want to be doing is trying to map this to a stream of one directional flow rather than sort of using the stream as a mutable object. Thus:
const pageStream = nextPage.pipe(
//Always trigger the first page to load
startWith(0),
//Load these pages asynchronously, but keep them in order
concatMap(
(_, pageNum) => from($http(...)).pipe(pluck('content'))
),
//One option of how to join the pages together
scan((pages, p) => ([...pages, p]), [])
)
;
If you need reset functionality I would suggest that you also consider wrapping that whole stream to trigger the reset.
resetPages.pipe(
// Used for the "first" reset when the page first loads
startWith(0),
//Anytime there is a reset, restart the internal stream.
switchMapTo(
nextPage.pipe(
startWith(0),
concatMap(
(_, pageNum) => from($http(...)).pipe(pluck('content'))
),
scan((pages, p) => ([...pages, p]), [])
)
).subscribe(x => /*Render page content*/);
As you can see, by refactoring to nest the logic into streams we can remove the global state that was floating around before
You can use Subject and separate the problem you are solving into 2 observables. One is for scrolling events , and the other is for retrieving data. For example:
let scrollingSubject = new Rx.Subject();
let dataSubject = new Rx.Subject();
//store the data that has been received back from server to check if a page has been
// received previously
let dataList = [];
scrollingSubject.subscribe(function(page) {
dataSubject.onNext({
pageNumber: page,
pageData: [page + 10] // the data from the server
});
});
dataSubject.subscribe(function(data) {
console.log('Received data for page ' + data.pageNumber);
dataList.push(data);
});
//scroll to page 1
scrollingSubject.onNext(1);
//scroll to page 2
scrollingSubject.onNext(2);
//scroll to page 3
scrollingSubject.onNext(3);
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.all.js"></script>

jstree select multiple nodes fire one event

I have a tree of files and am trying to create an editor for. When one node is selected a panel is loaded for that specific node. If multiple nodes are selected a more generic panel be loaded for all selected nodes.
The problem is, when selecting multiple nodes the "select_node.jstree" is fired for each node.
a snippet of related code...
$("#tree).on("select_node.jstree", function(event, node) {
var selected = node.instance.get_selected();
if(selected.length === 1) {
$("#editor").load(url);
} else if(selected.length > 1) {
$.post(url, {
data: selected
}, function(res) {
$("#editor").html(res);
});
}
});
So... with this if I select 5 items I am doing 1 GET and 4 POSTS.
What I am looking for is 1 GET (the first node selected) and 1 POST (the collection of selected nodes)...
Would it be just a timeout? I feel like I am missing something obvious. I am far from a good programmer, so any direction would be appreciated.
So, I was able to use doTimeout library to manage this. It works, not sure if it is optimal.
https://github.com/cowboy/jquery-dotimeout
$('#tree').on("select_node.jstree", function(event, node) {
$.doTimeout('select', 500, function () {
var selected = node.instance.get_selected();
if(selected.length === 1) {
$('#editor').load(url);
} else if(selected.length > 1) {
$.post(url, {
data: selected
}, function(res) {
$('#editor').html(res);
});
}
});
});

How to get dynamic element HTML use Addon SDK with Timers?

I want to scrape a page, the HTML content of this page auto change in a time frame. So i want to use pageMod and Timers of Addon Sdk to get the element innerHtml which change often.
Here are my scripts :
In main.js :
var tag = "container1";
var data = require("sdk/self").data;
var pageMod = require("sdk/page-mod");
var timer = require("sdk/timers");
var i = 0;
function scrapeData()
{
i = i + 1;
console.log("Begin pageMod : " + i);
pageMod.PageMod({
include: "*.test.com",
contentScriptFile: data.url("element-getter.js"),
contentScriptWhen: 'ready',
onAttach: function(worker) {
worker.port.emit("getElements", tag);
worker.port.on("gotElement", function(elementContent) {
console.log(elementContent);
});
}
});
console.log("End pageMod : " + i);
}
timer.setInterval(scrapeData, 10000);
And in data/element-getter.js :
self.port.on("getElements", function(tag) {
var elements = document.getElementById(tag);
self.port.emit("gotElement", elements.innerHTML);
});
After install this Firefox Add-on, when timers is running, it can only get the innerHtml one time, and the other time, it only display Begin pageMod and End pageMode in console log. Please help.
What you're currently doing is attaching the same page mod multiple times.
What you should do is move the timer inside the content script:
data/element-getter.js:
function scrapeData() {
var elements = document.getElementById(tag);
self.port.emit("gotElement", elements.innerHTML);
}
setInterval(scrapeData, 10000);
If you really want to keep the timer in the main page, then you need to maintain an array of worker instances, and loop through this array to emit your custom event. See this answer for more details.
(PS. Depending on your use case, the sdk/frame/hidden-frame module might be of interest.)

jsTree Node Expand/Collapse

I ran into the excellent jstree jQuery UI plug in this morning. In a word - great! It is easy to use, easy to style & does what it says on the box. The one thing I have not yet been able to figure out is this - in my app I want to ensure that only one node is expanded at any given time. i.e. when the user clicks on the + button and expands a node, any previously expanded node should silently be collapsed. I need to do this in part to prevent the container div for a rather lengthy tree view from creating an ugly scrollbar on overflow and also to avoid "choice overload" for the user.
I imagine that there is some way of doing this but the good but rather terse jstree documentation has not helped me to identify the right way to do this. I would much appreciate any help.
jsTree is great but its documentation is rather dense. I eventually figured it out so here is the solution for anyone running into this thread.
Firstly, you need to bind the open_node event to the tree in question. Something along the lines of
$("tree").jstree({"themes":objTheme,"plugins":arrPlugins,"core":objCore}).
bind("open_node.jstree",function(event,data){closeOld(data)});
i.e. you configure the treeview instance and then bind the open_node event. Here I am calling the closeOld function to do the job I require - close any other node that might be open. The function goes like so
function closeOld(data)
{
var nn = data.rslt.obj;
var thisLvl = nn;
var levels = new Array();
var iex = 0;
while (-1 != thisLvl)
{
levels.push(thisLvl);
thisLvl = data.inst._get_parent(thisLvl);
iex++;
}
if (0 < ignoreExp)
{
ignoreExp--;
return;
}
$("#divElements").jstree("close_all");
ignoreExp = iex;
var len = levels.length - 1;
for (var i=len;i >=0;i--) $('#divElements').jstree('open_node',levels[i]);
}
This will correctly handle the folding of all other nodes irrespective of the nesting level of the node that has just been expanded.
A brief explanation of the steps involved
First we step back up the treeview until we reach a top level node (-1 in jstree speak) making sure that we record every ancestor node encountered in the process in the array levels
Next we collapse all the nodes in the treeview
We are now going to re-expand all of the nodees in the levels array. Whilst doing so we do not want this code to execute again. To stop that from happening we set the global ignoreEx variable to the number of nodes in levels
Finally, we step through the nodes in levels and expand each one of them
The above answer will construct tree again and again.
The below code will open the node and collapse which are already opened and it does not construct tree again.
.bind("open_node.jstree",function(event,data){
closeOld(data);
});
and closeOld function contains:
function closeOld(data)
{
if($.inArray(data.node.id, myArray)==-1){
myArray.push(data.node.id);
if(myArray.length!=1){
var arr =data.node.id+","+data.node.parents;
var res = arr.split(",");
var parentArray = new Array();
var len = myArray.length-1;
for (i = 0; i < res.length; i++) {
parentArray.push(res[i]);
}
for (var i=len;i >=0;i--){
var index = $.inArray(myArray[i], parentArray);
if(index==-1){
if(data.node.id!=myArray[i]){
$('#jstree').jstree('close_node',myArray[i]);
delete myArray[i];
}
}
}
}
}
Yet another example for jstree 3.3.2.
It uses underscore lib, feel free to adapt solution to jquery or vanillla js.
$(function () {
var tree = $('#tree');
tree.on('before_open.jstree', function (e, data) {
var remained_ids = _.union(data.node.id, data.node.parents);
var $tree = $(this);
_.each(
$tree
.jstree()
.get_json($tree, {flat: true}),
function (n) {
if (
n.state.opened &&
_.indexOf(remained_ids, n.id) == -1
) {
grid.jstree('close_node', n.id);
}
}
);
});
tree.jstree();
});
I achieved that by just using the event "before_open" and close all nodes, my tree had just one level tho, not sure if thats what you need.
$('#dtree').on('before_open.jstree', function(e, data){
$("#dtree").jstree("close_all");
});