Some Dojo Tips

I recently joined a project that uses Python, PostgreSQL, and Dojo. I have not used any of these to any extent worth mentioning, so I’m learning quite a bit. I spent way too much time working on very simple bugs and thought I’d post the solutions I found here – hopefully to avoid anyone else spending more time on them than is necessary.

1. Use dojo.byId(…)

Okay, so this isn’t one that gave me a hard time, but I read about the cross-browser compatibility of using dojo.byId instead of document.getElementById and thought it would be worth mentioning in here. According to DojoToolkit.org, bugs persist in Internet Explorer which make getElementById() unstable in some common scenarios. Below is an example of one of these bugs:

<script type="text/javascript">
var elem = document.getElementById('myDiv'); // Returns form element
var elem2 = dojo.byId('myDiv'); // Returns div
</script>

<form>
<div id="myDiv">TESTING</div>
</form>

One of my least favorite things to do is debug IE errors. Save yourself the heartache and just dojo.byId if you have it available.

2. Use dojo.addOnLoad(…)

This one did give me trouble. I was unaware of the existence of this function until I had already spent a few hours trying to find out why my function wasn’t working. Here’s a simplified example of what I was doing:

<script type="text/javascript">
var button = dojo.byId('myButton');
var handle = dojo.connect(button, 'onclick', function (evt) { alert('test'); });
</script>

<input id="myButton" type="button" />

Theoretically, when I click the button, I should get an alert with the text “test”. However, as the code is, I get the alert when I click anywhere on the page. The problem? dojo.byId(‘myButton’) was returning null, adding my onclick event to every object on the page! Why was dojo.byId returning null for an object that clearly exists? I even went to my Firebug console and typed “dojo.byId(‘myButton’)”, which of course, return my input button as expected. I finally realized (duh) that my javascript code is executing before the input element exists. Proper usage of the addOnLoad function fixed the problem.

<script type="text/javascript">
dojo.addOnLoad(function(){
var button = dojo.byId('myButton');
var handle = dojo.connect(button, 'onclick', function (evt) { alert('test'); });
});
</script>

<input id="myButton" type="button" />

Hopefully these tips will help save you some time that I wasted. Do you have any quick dojo tips that could save me time? Let me know in the comments section!

Bookmark and Share
If you enjoyed this post, make sure you subscribe to my RSS feed!

Filed under JavaScript · Tagged with , , , ,

Speak Your Mind

Tell us what you're thinking...
and oh, if you want a pic to show with your comment, go get a gravatar!