Troubleshooting CSS Style Assignments within Dojo
I was recently working on a Dojo project which used a series of JavaScript calculations to generate CSS style values. While calculating styles with JavaScript is quite common, especially when attempting to dynamically position HTML nodes, values aren't always cleansed the way that they should be. Safari and Firefox appear to ignore invalid style values but Internet Explorer tends to throw errors when a bad style or value is assigned to a node. After digging through tons of code to find a possible problem, I chose create a modified dojo.style snippet which would help me find problem styles.
The Dojo Toolkit JavaScript
The snippet is actually quite small and only adds to Dojo's native dojo.style method:
//save original method var oldDojoStyle = dojo.style; //create our own custom version dojo.style = function() { //debug if(arguments.length == 3) { //make arguments readable var node = arguments[0], attribute = arguments[1], value = arguments[2]; //decide to warn or log var method = (value == undefined || value == null || value == '' || value.toString().indexOf('NaN') != -1 ? 'warn' : 'log' ); //execute! console[method]('Setting "' + attribute + '" to: "' + value + '" on ',node,';; arguments: ',arguments); } //call origonal method oldDojoStyle.apply(dojo, arguments); }
The first step is saving the original dojo.style method so it may be called from the new dojo.style method we create. Then we create a new dojo.style method declaration which contains a series of console.log/warn logic to output invalid CSS values, like null, undefined, and NaN. When a potentially bad value is provided, a console.warn warning is sent to the console.
A sample bit of output would be:
You could use an alert() call to make the error more noticeable but I prefer using console because I can pass the actual arguments object to the console to get more information about the issue.
And there you have it. I know this is super simple but it can also save you lots of time in finding what style assignment is causing you problems!
I did something similar once, but rather than monkey patching dojo.style, I just connected to it – something like this: http://jsfiddle.net/brianarn/k7aZG/
That way, I don’t have to save a reference to the original method. Arguably, it’s doing the same thing here (since connect is kind of like a fancy monkey patcher of sorts), but it just feels a bit cleaner to me.