JavaScript syntax and statements 29

Một phần của tài liệu JavaScript step by step, 3rd edition (Trang 43 - 55)

PART I JAVAWHAT? THE WHERE, WHY, AND HOW OF JAVASCRIPT

Chapter 3 JavaScript syntax and statements 29

Developing in JavaScript

After completing this chapter, you will be able to

■ Understand the options available for developing in JavaScript.

■ Configure your computer for JavaScript development.

■ Use Microsoft Visual Studio 2012 to create and deploy a JavaScript application.

■ Use Eclipse to create and deploy a JavaScript application.

■ Use Notepad (or another editor) to create a JavaScript application.

■ Understand options for debugging JavaScript.

JavaScript development options

Because JavaScript isn’t a compiled language, you don’t need any special tools or development envi- ronments to write and deploy JavaScript applications. Likewise, you don’t need special server software to run the applications. Therefore, your options for creating JavaScript programs are virtually limitless.

You can write JavaScript code in any text editor; in whatever program you use to write your Hypertext Markup Language (HTML) and cascading style sheet (CSS) files; or in powerful integrated development environments (IDEs) such as Visual Studio. You might even use all three approaches. You might initially develop a web application with Visual Studio but then find it convenient to use a simple text editor such as Notepad to touch up a bit of JavaScript. Ultimately, you should use whatever tool you’re most comfortable with.

This book doesn’t really discuss or give much specific direction on JavaScript editors; you can use whatever you want. With that said, when you get into developing for Windows 8, which is covered in

My own development environment

In case you think that this is a Microsoft-only JavaScript book, you might be surprised to learn that many of the examples that you will see were written in Vim, and tested in both Firefox and Internet Explorer.

Personally, I find Vim convenient, because it's readily available from just about anywhere.

It's lightweight, and gets out of the way. And Firefox provides excellent feeback through its Firebug add-on (which you'll see later). This combination has worked for me for years. How- ever, I don't tend to use Vim for the .NET work that I do; I find Visual Studio works better for Microsoft-centric development and for building websites that run solely on Microsoft technol- gies. The Windows 8 exaxmples shown in the book were created entirely in Visual Studio and take advantage of the Windows 8 JavaScript libraries.

After you’ve been developing JavaScript for a while, you’ll notice that you do some of the same things on every webpage. In such cases, you can just copy and paste the repeated code into the web- page that you’re developing. Better still, you can create an external file containing common functions that you can then use throughout the sites you develop. Chapter 7, “Working with functions,” has more information about functions, although you’ll see functions used throughout the book.

Configuring your environment

This section looks at JavaScript development using Visual Studio 2012. If you are comfortable using other editing tools, you might want to look at Appendix B, which discusses writing JavaScript with Eclipse and with plain text editors.

One useful JavaScript development tool is Visual Studio 2012. A simple web server—the ASP.NET Development Server—comes with the installation of Visual Studio 2012, which makes deploying and testing the applications in this book a little easier. However, you can still test the JavaScript code in this book with other IDEs, such as Eclipse. Likewise, you can test the JavaScript code even if you don’t use an IDE at all.

Another option for web development is Visual Studio 2012 Express for Web. This tool, available at http://www.microsoft.com/express, provides the Visual Studio interface and several tools and add-ons in a free package made just for web development. There is also an Express version for Windows 8 development available from that same URL.

You don’t absolutely need a web server for most JavaScript development. The notable exception to this is when you’re developing using Asynchronous JavaScript and XML (AJAX). AJAX cannot use the file:// protocol, which, in addition to the Same-Origin Policy covered in Chapter 1, “JavaScript is more than you might think,” prevents AJAX from working unless you use a web server. The bottom line: if AJAX development is in your future, you need a web server.

AJAX notwithstanding, development does become a little easier if you have a web server handy.

Any web server will work because all you really want to do is serve HTML and JavaScript, and maybe a little CSS for fun.

Configuring Apache or any web server is beyond the scope of this book, and again, having a web server is not required. The Apache website has some good tutorials for installing Apache on Windows, and if you’re using just about any version of Linux, Apache will likely be installed already or is easily installed. Many of the examples used in the book will work whether you’re using a web server or just viewing the example locally. However, a web server is necessary to take advantage of examples that use AJAX.

Writing JavaScript with Visual Studio 2012

Visual Studio 2012 lets developers quickly deploy web applications with JavaScript enhancements.

Visual Studio 2012 Express Edition is available as a free download at http://www.microsoft.com/

express, along with other tools related to development. Installation is typically a matter of executing the downloaded file from Microsoft, possibly installing a Web Platform installer first, but you should refer to the documentation for the latest information at the time of installation.

note The first portion of this book will use Visual Studio 2012 Express for Web, which includes the necessary templates for web-based JavaScript development. Windows 8 devel- opment uses a different set of templates, and those will be shown in the Windows 8 section of the book.

Your first web (and JavaScript) project with Visual Studio 2012

It’s time to create a web project and write a little JavaScript. If you’re not using Visual Studio, skip ahead in this chapter to the section “Writing JavaScript with Eclipse” or the section “Writing JavaScript without an IDE” for information about working in other development environments. I won’t forget about you, I promise!

note You can download the code found in these examples and throughout the book. See this book’s Introduction for directions about downloading the companion content.

2. Select ASP.NET Empty Web Site (the language selection—Visual Basic or Visual C#—is not important), as shown here. Change the name to jsbs, with a path appropriate to your configu- ration. When the information is correct, click OK. Visual Studio creates a new project.

3. Visual Studio 2012 creates an empty project for you... really empty, with not even so much as a default page. Create a new file by selecting New File from the File menu. The Add New Item dialog box opens, as shown in the following graphic. Select HTML Page, change the name to index.html, and then click Add. Visual Studio opens the new file and automatically enters the DOCTYPE and other starting pieces of an HTML page for you.

4. In the index.html page, place your cursor between the <TITLE> and </TITLE> tags, and change the title to My First Page. Your environment should look like the one shown here:

5. Between the opening <BODY> tag and the closing </BODY> tag, add the following code:

<script type="text/javascript">

function yetAnotherAlert(textToAlert) { alert(textToAlert);

}

yetAnotherAlert("This is Chapter 2");

</script>

6. Select Save All from the File menu. The finished script and page should resemble the screen shown here:

7. To view the page, select Start Debugging from the Debug menu. This starts the ASP.NET Development Server (if it’s not already started) and takes you to the page in your default browser. You might see a dialog, like the following, indicating that the debugging isn’t enabled in your web.config. Click OK to dismiss this dialog (and enable debugging).

Now you should receive a page with an alert, similar to the alert shown here:

8. Click OK, and then close the browser.

The script works as follows. First, the script tag is opened and declared to be JavaScript, as shown by this code:

<script type="text/javascript">

note You can declare your script is JavaScript in other ways, but the approach you see here is the most widely supported.

Next, the script declares a function, yetAnotherAlert, which accepts one argument, textToAlert, as follows:

function yetAnotherAlert(textToAlert) {

The function has one task: to pop an alert into the browser window with whatever text has been supplied as the function argument, which the next line accomplishes:

alert(textToAlert);

The end of the function is delineated by a closing brace (}). The next line of the script calls the function you just declared with a quoted string argument:

yetAnotherAlert("This is Chapter 2");

With this script, you’re ready to develop JavaScript in Visual Studio 2012. But before you celebrate, consider sticking with me and learning about how to use external files to store your JavaScript code.

Using external JavaScript files with Visual Studio 2012

JavaScript files means that you can maintain common JavaScript code in one place, as opposed to maintaining it within each individual page—which will save you a lot of work.

At this point, you should have a working webpage (built using Visual Studio) that displays an alert, thanks to some nifty JavaScript. The webpage you developed in the previous section contains the JavaScript code within the <BODY> portion of the page. In the following section, I show you how to place JavaScript into an external file and then reference that code from within your HTML page.

Creating an external file for JavaScript using Visual Studio 2012

1. If the index.html file isn’t open, open it by going into Visual Studio and selecting Open Project from the File menu. Select the project in which you saved the index.html file (available in the companion content as firstindex.html), and open the file. Your environment should look some- thing like the environment in step 6 in the previous example.

2. Create a new file to hold the JavaScript code by selecting New File from the File menu. The Add New Item dialog box appears. In the list of templates, select JavaScript File and change the name to myscript.js, as shown in the following screen, and then click Add. Note that your list might differ depending on your Visual Studio installation. You can find this source file, titled myscript.js, in the Chapter 2 sample code.

note If you see only JScript file instead of JavaScript file, you might not have the Express Edition for Web of Visual Studio 2012. However, a JScript file type will work just fine.

3. A new empty JavaScript file opens and is added to your web project. You should see a tab for the new myscript.js file and another for the index.html file, as shown in the next screen. If the index.html file isn’t opened in a tab, open it by double-clicking it in the Solution Explorer.

note The colloquial extension for JavaScript and JScript is .js, but you are not required to use it. I chose to use a JavaScript type of file in the preceding step 2 because this file type automatically selects the correct file extension. You could just as easily have selected Text Document from the Add New Item dialog box and then named the file with a .js extension.

4. Click the index.html tab to make it active, and highlight the JavaScript code in between the opening and closing <SCRIPT> tags. Don’t copy the <SCRIPT> tags themselves.

5. Copy the highlighted code to the Clipboard by selecting Copy from the Edit menu.

7. Save the myscript.js file by selecting Save from the File menu. The file should look like the following:

8. With the JavaScript code contained in its own file named myscript.js (you did save that file, right?), you can just delete the code from the index.html file, including the opening and clos- ing <SCRIPT> tags.

9. Inside the <HEAD> section, after the closing </TITLE> tag, place the following:

<script type="text/javascript" src="myscript.js"></script>

The entire contents of index.html should now be the following:

<!DOCTYPE html>

<html>

<head>

<title>My First Page</title>

<script type="text/javascript" src="myscript.js"></script>

</head>

<body>

</body>

</html>

10. Save index.html.

11. View the page in a web browser by selecting Start Debugging from the Debug menu. The page will be served through the web server, and your browser window, if not already open, will open to the page. The result should be an alert with the text “This is the Second Example.”

An example of this is shown here:

12. Click OK to close the alert dialog box.

You’ve developed JavaScript with Visual Studio 2012. From here, you can skip ahead to the section on debugging or see Appendix B: Writing JavaScript with Other Tools to learn about JavaScript devel- opment using other tools.

Debugging JavaScript

Debugging JavaScript can be an alarming experience, especially in more complex applications. Some tools, such as Venkman (http://www.mozilla.org/projects/venkman/), can assist in JavaScript debug- ging, but the primary tool for debugging JavaScript is the web browser. Major web browsers include some JavaScript debugging capabilities. Among the programs you should consider using is Firebug, a notable add-on to Firefox. Firebug is available at http://www.getfirebug.com/.

I find Firebug to be virtually indispensable for web development, especially web development with JavaScript and AJAX. This software enables you to inspect all the elements of a webpage and to see the results of AJAX calls and CSS, all in real time, which makes debugging much easier. Later in the book, you’ll see more on Firebug.

I recommend using Firebug for developing JavaScript and debugging it. When debugging JavaScript, I find that the alert() function is quite useful. A few well-placed alert() functions can show you the values contained within variables and what your script is currently doing. Of course, because alert() causes a dialog box to open, if you place an alert() within a loop and then mistakenly cause that loop to repeat endlessly without exiting, you’ll find that you need to exit the web browser uncleanly, perhaps using Task Manager.

2. Edit the webpage that you created in Exercise 1, create a function within the <HEAD> portion of the page, and move the alert() dialog box that you currently have in the <BODY> script into your new function. Call the new function from the existing <BODY> script.

3. Move the function created in Exercise 2 to an external JavaScript file, and link or call this file from within your webpage.

Một phần của tài liệu JavaScript step by step, 3rd edition (Trang 43 - 55)

Tải bản đầy đủ (PDF)

(481 trang)