Customizing the Data Table Widget, Part VI

“A person who never made a mistake never tried anything new.”
Albert Einstein

Well, it turns out it didn’t take all that long to figure out why I was losing the buttons and icons on my customized Data Table widget whenever I sorted the data. It was definitely my fault, which was easily predictable based on the The First Rule of Programming. I actually had one of those this is not right feelings at the time that I did it, but I ignored that and did it, anyway. When I was parsing the JSON string for the button configuration to obtain the actual JSON array of button specs, I reused the same variable to hold the array as the original variable that held the string. Here is the offending code:

if (data.buttons) {
	try {
		var buttoninfo = JSON.parse(data.buttons);
		if (Array.isArray(buttoninfo)) {
			data.buttons= buttoninfo;
		} else if (typeof buttoninfo == 'object') {
			data.buttons = [];
			data.buttons[0] = buttoninfo;
		} else {
			gs.error('Invalid buttons option in SNH Data Table widget: ' + data.buttons);
			data.buttons= [];
		}
	} catch (e) {
		gs.error('Unparsable buttons option in SNH Data Table widget: ' + data.buttons);
		data.buttons = [];
	}
} else {
	data.buttons = [];
}

The problem with doing that, which is just a bad practice in general and I’ve been around long enough to know better, is that we pass through this same code again and again whenever the table is sorted. Reusing the same variable means that when you come through this logic the next time around, things are not the same as they were the first time through. That’s not good. I tried several failed attempts at detecting and avoiding the problem, but I finally broke down and just created a new variable to hold the button spec array and left the original JSON string intact. That solved the problem. Here is what it looks like now:

if (data.buttons) {
	try {
		var buttoninfo = JSON.parse(data.buttons);
		if (Array.isArray(buttoninfo)) {
			data.btnarray = buttoninfo;
		} else if (typeof buttoninfo == 'object') {
			data.btnarray = [];
			data.btnarray[0] = buttoninfo;
		} else {
			gs.error('Invalid buttons option in SNH Data Table widget: ' + data.buttons);
			data.btnarray = [];
		}
	} catch (e) {
		gs.error('Unparsable buttons option in SNH Data Table widget: ' + data.buttons);
		data.btnarray = [];
	}
} else {
	data.btnarray = [];
}

Of course, once I changed the name of the variable, then I had to hunt down and modify every reference to that variable, which was a task in itself. But I’ve done the work now, and retested everything, so here’s another Update Set with the corrected code. Lesson learned (yeah, right!).