onLoadEnd parent task id


#1

I have implemented on demand data loading and i need to sort the currently loaded childs by end_date for example.

gantt.sort function’s third parameter will do the trick but how do i know the parent id of the currently loaded branch? What if the user clicks multiple tasks to load at the same time?


#2

Hello Nikolai,
onLoadEnd event handler doesn’t have the ID parameter. But you can use onTaskLoading event handler to get the ID of the first task that is being loaded.
To see how it works, you can apply the following code in the branch_loading sample:
https://docs.dhtmlx.com/gantt/samples/02_extensions/06_dynamic_loading.html

var load_id = null;
gantt.attachEvent("onTaskLoading", function(task){
    if (!load_id) load_id = task.id
    return true;
});

gantt.attachEvent("onLoadEnd", function(){
    var parent = gantt.getTask(load_id).parent;
	gantt.sort("start_date",false,parent);
	load_id = null;
});

If user clicks to open several branches before one branch is loaded (and so before the onLoadEnd event is fired), you need to implement more complex solution. The easiest way would be to add a custom button that will control the clicks (and it allows to get the task ID). Otherwise, you need to get the IDs of all tasks that are loaded, then you need to check if those tasks belong to the same branch. Here is the example:

var loaded_ids = [];
gantt.attachEvent("onTaskLoading", function(task){
    loaded_ids.push(task.id)
    return true;
});

gantt.attachEvent("onLoadEnd", function(){
	var branches = [];
	var temp_id;
	for (var i = 0; i < loaded_ids.length; i++) {
		if (loaded_ids[i] != temp_id){
			temp_id = loaded_ids[i];
			branches.push(temp_id);
        }
	}
	for (var i = 0; i < branches.length; i++) {
		var parent = gantt.getTask(branches[i]).parent;
		gantt.sort("start_date",false,parent);
	}
    
	branches = [];
});

#3

Could you please check if the second source code is correct because the sort event is fired as many times as the loaded_ids array length is.


#4

Hello Nikolai,
Sorry, looks like there were other things that I didn’t test. Here is the updated code:

var loaded_ids = [];
gantt.attachEvent("onTaskLoading", function(task){
    loaded_ids.push(task.id)
    return true;
});

gantt.attachEvent("onLoadEnd", function(){
	var branches = [];
	var temp_id;
	for (var i = 0; i < loaded_ids.length; i++) {
		var parent = gantt.getTask(loaded_ids[i]).parent;
		if (parent != temp_id){
			temp_id = parent;
			branches.push(temp_id);
        }
	}
	for (var i = 0; i < branches.length; i++) {
		
		gantt.sort("start_date",false,branches[i]);
	}
    
	loaded_ids = [];
});

gantt.attachEvent("onAfterSort",function(field, direction, parent){
    gantt.message("onAfterSort")
});

Now the sort event fires only for the branch that you open.