- Use Include Files
- Use Consistent Document Structure
- Bind Granular Functions to Events
- JavaScript Style Conventions
- Summary
Bind Granular Functions to Events
Listing 1 illustrates one method for binding a function to an event. There is an alternative syntax for attaching functions to events. The <script> tag offers the for and event attributes. The for attribute allows the developer to specify that the script is bound to a certain element, while the event attribute specifies the event that it is bound to. So, Listing 3 is also functionally exactly the same as Listing 1.
Listing 3: Alternative Syntax for Binding a Client-Side Script to an Event
<html> <head> <title></title> <script language="JavaScript"> var nCount = 0; // Executes when document loads alert("Count is " + nCount); // So does this </script> <script language="JavaScript" for="btnIncrement" event="onclick"> alert(++nCount); // Executes only when doCount is called </script> </head> <body> <input id="btnIncrement" type="button" value="Increment"> </body> </html>
While binding functions to events is the preferred method of associating functionality with an event, the trouble with this alternative for doing so is that the entire script block is associated with the specified element and event. This eliminates the capability to leverage a single script for multiple elements. For this reason, the method illustrated back in Listing 1 is preferred.
This preferred method also promotes the use of granular, generic functions as opposed to large, monolithic functions that try to do many things. Code is easier to read, maintain, and reuse if functionality is implemented in smaller pieces.