0

I need to create 14 javascript Ajax objects and assign properties and events to them. Since most of the code is just being repeated, I'd like to do the whole thing in a loop using an array for the object names.

This is a portion of the code as it now stands:

boxe2_tree = new dhtmlXTreeObject("boxe2_div", "100%", "100%", 0);
boxe2_tree.enableCheckBoxes(1);
	// etc.
boxe2_tree.loadXML("./xml/boxe.xml",function(){loadTree('boxe2_tree');});
			
warn2_tree = new dhtmlXTreeObject("warn2_div", "100%", "100%", 0);
warn2_tree.enableCheckBoxes(1);
	// etc.
warn2_tree.loadXML("./xml/warn.xml",function(){loadTree('warn2_tree');});
	// Continue for 12 more trees

And this is what I would like to do:

var arTrees = new Array('boxe', 'warn', 'safe', 'indi', 'desc', 'dosa', 'stud'); // etc.
for (x in arTrees){
	var treeName = arSections[x] + "2_tree";
	treeName = new dhtmlXTreeObject(arSections[x] + "_div", "100%", "100%", 0);
	treeName.enableCheckBoxes(1);
	// etc.
	treeName.loadXML("./xml/" + arSections[x] + ".xml");
}

I tried using eval, but I couldn't get it to work.

I'd appreciate any help anyone can offer.

2
Contributors
3
Replies
4
Views
6 Years
Discussion Span
Last Post by Airshow
0

Agrarian, eval should be avoided and is generally unnecessary.

Easiest thing is to use the tree names as properties of an object:

var arTreePrefixes = ['boxe', 'warn', 'safe', 'indi', 'desc', 'dosa', 'stud'];// etc.
var arTrees = {};//new Object
for (var i=0; i<arTreePrefixes.length; i++) {
	var treeName = arTreePrefixes[i] + "2_tree";
	arTrees[treeName] = new dhtmlXTreeObject(arTreesPrefixes[i] + "_div", "100%", "100%", 0);//?
	arTrees[treeName].enableCheckBoxes(1);
	arTrees[treeName].loadXML("./xml/" + arTreePrefixes[i] + ".xml");//?
}

Airshow

Edited by Airshow: n/a

0

Airshow,

Thanks for the reply!

Later, I need to be able to call functions like:

function loadTree(treeName){
	var elmTree = window[treeName];
	if (elmTree != null){
		elmTree.loadOpenStates(treeName);
		loadCheckedStates(treeName);
	}
}

Currently, I just pass treeNames such as "boxe2_tree" to these functions. Would that work if I followed your suggestion? It looks like you've created an array which may make things a little more complicated.

0

Agrarian,

Address the trees in the arTrees object in exactly the same way as if they were in the global (window) namespace.

function loadTree(treeName) {
	var elmTree = arTrees[treeName];
	if (elmTree){
		elmTree.loadOpenStates(treeName);
		loadCheckedStates(treeName);
	}
}

Providing arTrees is in scope (and assuming your method/function calls are correct), this should work.

Airshow

Edited by Airshow: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.