<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	>

<channel>
	<title>agum &#187; JavaScript</title>
	<atom:link href="http://www.agum.com/web/category/javascript/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.agum.com/web</link>
	<description>The Web Dev Blog</description>
	<pubDate>Mon, 23 Jun 2008 10:47:45 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.5.1</generator>
	<language>en</language>
			<item>
		<title>JavaScript: Using Event Listeners, attaching handlers on page load, and DOMContentLoaded</title>
		<link>http://www.agum.com/web/2008/03/21/javascript-using-event-listeners-attaching-handlers-on-page-load-and-domcontentloaded/</link>
		<comments>http://www.agum.com/web/2008/03/21/javascript-using-event-listeners-attaching-handlers-on-page-load-and-domcontentloaded/#comments</comments>
		<pubDate>Sat, 22 Mar 2008 04:03:15 +0000</pubDate>
		<dc:creator>Bigi</dc:creator>
		
		<category><![CDATA[AJAX]]></category>

		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://www.agum.com/web/2008/03/21/javascript-using-event-listeners-attaching-handlers-on-page-load-and-domcontentloaded/</guid>
		<description><![CDATA[For anybody who has ever coded any JavaScript at all, they are no doubt familiar with events such as &#8220;onclick&#8221;, &#8220;onmouseover&#8221;, &#8220;onmousemove&#8221;, and more. In old HTML web pages, it was very common to add these attributes to &#60;a&#62; tags to achieve some special effects.
Later on, browsers begin to support these attributes even in other [...]]]></description>
			<content:encoded><![CDATA[<p>For anybody who has ever coded any JavaScript at all, they are no doubt familiar with events such as &#8220;onclick&#8221;, &#8220;onmouseover&#8221;, &#8220;onmousemove&#8221;, and more. In old HTML web pages, it was very common to add these attributes to &lt;a&gt; tags to achieve some special effects.</p>
<p>Later on, browsers begin to support these attributes even in other tags like &lt;div&gt;, and pretty much anything else.</p>
<p>However, as web standards develop over the years and people&#8217;s coding practices for the web begin to standardize, it is generally considered bad practice to use them. There are many reasons for this, among others:</p>
<ol>
<li>You cannot attach more than 1 action this way. If you want to do a lot of things in one event, you will need to put a lot of code either in this attribute, or in the function being called from this attribute; and these may very well be unrelated actions. This makes your code less organized and harder to develop.</li>
<li>No good separation of presentation (HTML) from functionality (JavaScript). Everything is mixed together. This makes collaboration development efforts difficult; and makes the code hard for you to manage even if you were the sole developer.</li>
</ol>
<p>Fortunately, we have an alternative solution. They are Event Listeners.</p>
<p><span id="more-30"></span><br />
<strong>Event Listeners basics</strong></p>
<p>Event listeners are initiated strictly in JavaScript code, not within any HTML tags.</p>
<p>For the remaining of this article, I will assume the use of the <a href="http://www.prototypejs.org/">Prototype.js</a> framework. I&#8217;m aware that there are advanced developers who dislike this library, but it is used fairly commonly (either completely, or their own in-house modified version) among a lot of startups and web apps, so hopefully it&#8217;s not unreasonable to depend on it.</p>
<p>With that in mind (with the inclusion of Prototype.js), you can initiate an event listener like this. Assuming you defined a function for handling the &#8220;click&#8221; event on a div block with an id &#8220;main_div&#8221;:</p>
<blockquote>
<pre>var handlerFunction = function(event) {
alert('Hello world!');
};</pre>
<pre>var my_box = document.getElementById('main_div');
Event.observe(my_box, 'click', handlerFunction);</pre>
</blockquote>
<p>The main idea is very simple. It is simply this: instead of using onclick (or on-* of any event) in any HTML tags, you have Event.observe in your JavaScript code instead. This way, you can add as many different functions as you like to any elements. They can even come from different .js files. (for more details on how to use Event.observe, see the <a href="http://www.prototypejs.org/api/event/observe">Prototype.js documentation</a>.)</p>
<p>To see what kind of events are available to you other than &#8220;click&#8221;, see the <a href="http://www.w3.org/TR/DOM-Level-2-Events/events.html">DOM Events W3C spec</a>. What you will often be using are in section 1.6.2, mouse events.</p>
<p><strong>Page loading, and Initialization routine</strong></p>
<p>If you understand what the above code means, you can also logically deduce that, your event handler does not start being observed until the point this JavaScript runs. And whether you want it or not, when the Event.observe line executes, it will start.</p>
<p>The implication here is that, it is entirely possible that your HTML document is not ready to handle this. This is because JavaScript runs linearly as your HTML file is being loaded and parsed.</p>
<p>More often than not, your JavaScript resides in the beginning of your file. (It is recommended for web developers to keep their JavaScript at the top)  That means you don&#8217;t even have any objects on your HTML page yet! Your Event.observe line is sure to fail, because the object by the id &#8220;main_div&#8221; does not exist yet.</p>
<p>So should you put your JavaScript at the end of your page instead? Of course not! What you want is a way to run all your Event.observe lines <em>after your page is fully loaded</em>.</p>
<blockquote>
<pre>Event.observe(window, 'load', function() {
Event.observe(my_box, 'click', handlerFunction);
// ... any other event listeners go here
});</pre>
</blockquote>
<p>Once you have this in your JavaScript, all your event listeners will only initiate after your page is completely loaded. The way this works is simple. The &#8220;window&#8221; element means the entire browser window. The &#8216;load&#8217; event for this element means that this handler function will execute when the page is done loading. So the effect is that all your interactive elements on your page will start being interactive when the page is fully loaded.</p>
<p><strong>DOMContentLoaded</strong></p>
<p>But there is still a problem! The key word in the last paragraph was &#8220;fully loaded&#8221;. What this means is, your interactive elements only work <em>after</em> your entire page is ready. Unfortunately, this means after all images and other binary data have finished loading. When your web page is heavy with data, this might be a long time. If you use event listeners for your navigation dropdown menus, for example, that means they are not going to work until all your images are done loading. It would be very annoying if a user cannot use your navigation menu before the page finishes loading.</p>
<p>*This is why I wrote this article!* The key point is here.</p>
<p>Fortunately, thanks to many wise web developers on the internet, we now have a solution. This solution lets you initialize your event listeners as soon as your HTML finishes loading, and <em>without having to wait for images and all other data on your page</em>.</p>
<p>The solution: <a href="http://tanny.ica.com/ICA/TKO/tkoblog.nsf/dx/domcontentloaded-for-browsers-part-iv">DOMContentLoaded</a>.</p>
<p>In simple words, this events.js library will let you do this:</p>
<blockquote>
<pre>addEvent(window, "DOMContentLoaded", function() {
Event.observe(...);
// ...
});</pre>
</blockquote>
<p>What will happen now is that, all your event listeners will initiate as soon as the HTML of your page is loaded, without having to wait for anything else. I am not going to go through the details of how and why here (I try to make my blog as close to practical usage lessons as possible without being too academic). If you are interested, the link I gave you above should give you every detail you want.</p>
<p><strong>Conclusion</strong></p>
<p>With all of the above knowledge, there is absolutely no reason one should be using the old ways of &#8220;onclick&#8221;, &#8220;onmouseover&#8221;, etc. anymore. Many people attempt to use event listeners, but oftentimes they encounter the problem I stated above of elements having to wait for the page to be fully loaded to become interactive. This has turned many people back to using the old-school methods, which is unhealthy.  After having introduced you to DOMContentLoaded, it should solve all concerns you have with using event listeners.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.agum.com/web/2008/03/21/javascript-using-event-listeners-attaching-handlers-on-page-load-and-domcontentloaded/feed/</wfw:commentRss>
		</item>
		<item>
		<title>JavaScript: jslint, data types, &#8220;null&#8221; and &#8220;undefined&#8221;</title>
		<link>http://www.agum.com/web/2008/02/27/javascript-jslint-data-types-null-and-undefined/</link>
		<comments>http://www.agum.com/web/2008/02/27/javascript-jslint-data-types-null-and-undefined/#comments</comments>
		<pubDate>Wed, 27 Feb 2008 20:52:33 +0000</pubDate>
		<dc:creator>Bigi</dc:creator>
		
		<category><![CDATA[JavaScript]]></category>

		<guid isPermaLink="false">http://www.agum.com/web/2008/02/27/javascript-jslint-data-types-null-and-undefined/</guid>
		<description><![CDATA[Straight to the point: If you want to get one thing out of this article, get this:
In JavaScript, &#8220;null&#8221; is not the same as &#8220;undefined&#8221;.
This was what costed me some debug time recently when working with JavaScript at my job.  I will talk about how I came across this issue, because there are various valuable [...]]]></description>
			<content:encoded><![CDATA[<p>Straight to the point: If you want to get one thing out of this article, get this:</p>
<p><strong>In JavaScript, &#8220;null&#8221; is not the same as &#8220;undefined&#8221;.</strong></p>
<p>This was what costed me some debug time recently when working with JavaScript at my job.  I will talk about how I came across this issue, because there are various valuable aspects of this story that could be worth reading for those of you frontend developers.</p>
<p>Actually, scratch that, if you don&#8217;t know about jslint, <strong>do</strong> read the following section too. It is useful, and you won&#8217;t regret it.</p>
<p><span id="more-27"></span><strong>jslint</strong></p>
<p>First of all, most of you know that JavaScript is a pretty loosely-enforced language.  Most browsers out there (IE, Firefox, etc.) are pretty tolerant to sloppy code, just like HTML. To be fair, it&#8217;s not the browsers&#8217; faults completely, since in a lot of cases, JavaScript was defined to be like that. For example, it tolerates missing semi-colons at the end of a line. Nonetheless, JavaScript is very powerful, despite these problems that make programmmers cringe. Here&#8217;s a good read: <a href="http://www.crockford.com/javascript/javascript.html">JavaScript: The World&#8217;s Most Misunderstood Programming Language</a>.</p>
<p>The problem comes when there are multiple browsers. Each can interpret things a little differently. With <a href="https://addons.mozilla.org/en-US/firefox/addon/1843">Firebug</a> and <a href="http://www.mozilla.org/projects/venkman/">Venkman</a>, it&#8217;s easy to develop for Firefox and pinpoint errors. (I personally just use Firebug, in the short time I&#8217;ve tried Venkman, I found it too complicated.) For IE, this is a lot harder. The best free tool I&#8217;ve found is <a href="http://www.microsoft.com/downloads/details.aspx?familyid=2F465BE0-94FD-4569-B3C4-DFFDF19CCD99&amp;displaylang=en">MS Script Debugger</a> (free but requires genuine Windows <img src='http://www.agum.com/web/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> ), possibly along with <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=E59C3964-672D-4511-BB3E-2D5E1DB91038&amp;displaylang=en">IE Developer Toolbar</a> (completely free). IE Developer Toolbar is similar to Firebug, but without the JavaScript part. (only CSS and DOM inspecting)</p>
<p>With simple JavaScripts, debugging is usually not a problem. But when you get into object-oriented JavaScript, involving code spreaded out to many files, (IE&#8217;s internal-secret-line-numbering doesn&#8217;t help) it&#8217;s a nightmare. Couple this with the fact that IE has their own strange interpretation rules, you often cannot find where errors are happening.</p>
<p>Fortunately,  Douglas Crockford developed an extremely useful tool, called <a href="http://www.jslint.com/">jslint</a>. It&#8217;s even web-based (developed with JavaScript itself!), so you don&#8217;t have to install anything. All you do is copy and paste your JavaScript in there, and let it validate. Kind of like a <a href="http://validator.w3.org/">w3c validator</a> for HTML, also kind of like a compiler for C++. The lint program is/can be very strict on your code &#8212; this means if your code passes jslint, it is extremely likely that it will work fine in all browsers including IE.</p>
<p><strong>Data types comparisons</strong></p>
<p>In JavaScript, there are a few basic data types you&#8217;ll be using a lot, such as integers, strings, booleans. Because of the loosely-enforced nature of JavaScript, comparisons are made to be loose as well. To give an example of what I mean:</p>
<blockquote><p><code>var mynum = 0;<br />
var mybool = false;<br />
if (mynum == false) // this evalutes to true<br />
if (mybool == 0) // this evalutes to true</code></p></blockquote>
<p>They are all the same in &#8220;value&#8221;. To further enforce your code logic to make sure you&#8217;re doing what you want to do, jslint recommends using === or !== to check for equalities/inequalities when one side involves zero, false, null, empty string, etc. The === or !== operators also check the <em>data type</em>. To give an example, continuing from above:</p>
<blockquote><p><code>if (mynum === false) // this evalutes to false<br />
if (mynum === 0) // this evalutes to true</code></p></blockquote>
<p>Once you understand this part, let&#8217;s move on to the next section.</p>
<p><strong>&#8220;null&#8221; and &#8220;undefined&#8221;</strong></p>
<p>In JavaScript, they are different. Null is a value that is only assigned by a programmer. You can set a certain variable to the value null. Undefined is what a variable has if it wasn&#8217;t assigned to anything.</p>
<p>I had no idea about any of this before, so I googled it up and found this article: <a href="http://blog.techsaints.com/2007/04/25/javascript-difference-between-null-and-undefined/">JavaScript Difference Between null and undefined</a>. It has a clear and simple example to demonstrate the point. To be more specific about the kind of problems I ran into, we had something like this in our code.</p>
<blockquote><p><code>myFunc = function(arg1, arg2, arg3) {<br />
if (arg3 == null) {<br />
// do something<br />
}<br />
};</code></p></blockquote>
<p>This was working fine at first. If you call myFunc without arg3, it goes in the conditional statement and executes whatever is inside. When I ran the code through jslint, and changes the check to (arg3 === null) as it recommends, problems arose. It never went into that condition anymore and the bug travelled very far along the code to some weird behaviors. (because this function happened to be the constructor for a class in our case, making it hard to find at once)</p>
<p>I eventually realized that, when you don&#8217;t pass in arg3 to myFunc, arg3 then has the value &#8220;undefined&#8221;. The value, without the type, is the same as &#8220;null&#8221;. Initially, it worked fine when we only use ==. But when we add in type-checking, with ===, they are not the same. Thus, the code needed to be fixed to say:</p>
<blockquote><p><code>if (arg3 === undefined)</code></p></blockquote>
<p><strong>Conclusion</strong></p>
<p>It was a good lesson to me. Even though I&#8217;m coding up object-oriented JS left and right, there are still basics about the language that I admit I&#8217;m not familiar with. I learned something, and I hope you learned something out of this entry as well.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.agum.com/web/2008/02/27/javascript-jslint-data-types-null-and-undefined/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>

<!-- Dynamic Page Served (once) in 0.388 seconds -->
