ผลต่างระหว่างรุ่นของ "01219245/javascript1/tutorial2"
Jittat (คุย | มีส่วนร่วม) |
Jittat (คุย | มีส่วนร่วม) |
||
แถว 260: | แถว 260: | ||
== Let's write our game == | == Let's write our game == | ||
+ | |||
+ | Let's create a new directory '''<tt>guess</tt>''' and create a new Git repository in that directory. We shall re-write our number guessing game here. |
รุ่นแก้ไขเมื่อ 02:15, 22 มกราคม 2557
- This is part of 01219245
While the sequential-style interaction as in our previous tutorial is easy to write, the pop-ups is not a nice way to interact with users. Most UI application uses another programming model, called event-driven programming. In this tutorial, we shall learn how to do that in JavaScript. While event-driven programming is easy to do in JavaScript, it will be more entertaining to use a famous jQuery library to simplify various tasks.
This time we will not use jsFiddle, but we will write an easy web-application in your laptop/notebook/pc. We will also use Git to keep track of our development.
To help you to get familiar with Git, we will commit a lot in this tutorial. In real project we will commit when we make some "unit" of changes and might not commit as often as in this tutorial.
เนื้อหา
The plan
In this tutorial, we will re-implement the number guessing game we did previously so that it works like a typical web application.
The game should look like this:
From that, let's think a bit about what we have to do (or have to learn how to do).
Think
Don't read further until you have thought carefully about the above question.
Steps
What we have to do:
- Read a guess from the user.
- If we look more carefully into this step, we have to wait until the user press the button, then take the number in the text box.
- Check the guess.
- Update the result.
In GUI application, there are many "pieces" of the UI that the user can interact. For example, in the application above, if we want to add another button, called "Clear", that clear the text input, the user can either press the "Guess" button or the "Clear" button. It is hard for usual sequential program that waits for the user input to deal with many things at the same time. A better way to deal with these kinds of application is to think about the events that can occur and write programs that handle them. This is the idea of an event-driven programming.
First try at event-driven programming and jQuery
In this section, we shall experiment with the concepts and tools that we will use to re-write our number guessing game, namely, event-driven programming and jQuery.
Create a new directory called guessingprep. Create a new Git repository there.
Let's create an empty web page with a button. Create a file index.html with the following:
<!doctype html>
<html lang="en">
<body>
<button>Click me!</button>
</body>
</html>
View the page on a browser. (Note: enter file:/// into the URL bar, and keep browsing.) You should see the button. Clicking at it won't make anything happens.
Right now, it's a nice place to commit our changes to the Git repository.
git add index.html git commit -m "an empty page with a button"
Let's add a simple interaction. An onclick (from on click) attribute at a button element specify a JavaScript code that should be executed if the button is clicked. Change the button line to:
<button onclick="alert('Hello!');">Click me!</button>
Reload the page, and try clicking at the button.
Let's commit again. Put your own commit message.
git commit -am "________________________________"
Later on, I'll signal you where you should commit, you must add the commit message by yourself.
Including JavaScript in a web page
If we want to do complex things when a button is clicked, placing all the code in the onclick attribute is a mess. We shall write a function to do the work, and just call the function inside the onclick attribute.
There are two ways to include the JavaScript code in a web page. We can write a JavaScript code in a file and place a link to that file in our html page. We can also put the code directly inside the html page; this is call inline JavaScript. We shall write an inline JavaScript code for now.
A JavaScript code is placed inside a script block. Change index.html to the following:
<!doctype html>
<html lang="en">
<body>
<button onclick="update();">Click me!</button>
<script type="text/javascript">
var c = 0;
function update() {
c++;
alert(c);
}
</script>
</body>
</html>
Note a weird indentation. To help writing JavaScript code better, I remove one-step of indentation from the script block.
- You should click to play with it, if it works, commit the change.
You can add onclick attributes to buttons, links, and many elements. If we have to do that for many elements in the web page, it can be very messy. jQuery has a nice way we can deal with this mess.
Using jQuery
jQuery is a wonderful library that facilitates many tasks in JavaScript.
Go to jQuery's homepage, go to its download page, and download the compressed, production jQuery. While the filename should look like jquery-1.X.X.min.js, save the jquery script as jquery.js.
To include the library into our web page, add the following line
<script src="jquery.js"></script>
before our previous script block. This is how you include an external JavaScript to an html page.
With jQuery, instead of attaching the onclick attribute to the DOM elements, we will add the handler to the elements in the JavaScript source.
NOTES: We usually calls the elements in an HTML page a DOM element, where DOM stands for Document Object Model.
Selectors
What jQuery provides us is a function $. (You are right; the function name is just a dollar sign.) This function is used to query the DOM elements so that we can work on them. Let's see that by examples.
Let's remove the onclick attribute from the button, and add a line:
$("button").click(update);
to the end of the script block.
The complete index.html should look like this:
<!doctype html>
<html lang="en">
<body>
<button>Click me!</button>
<script src="jquery.js"></script>
<script type="text/javascript">
var c = 0;
function update() {
c++;
alert(c);
}
$("button").click(update);
</script>
</body>
</html>
The weird statement we have just added falls into a common idiom for using jQuery:
$(selector).dosomething().dosomethingmore().dosomethingfurthermore();
The selector button selects all button elements in the page. The .click(update); part registers function update to the onclick event.
- Try the code, and commit the current changes.
Two buttons: id and class
Let's add another button. Add the following line after the first button:
<button>Don't click me</button>
Before actually trying, what do you think will happen if you click this new button? Will the alert box appear? Why?
Now, let's try it. Do you know why?
If we don't want function update to run when the second button is clicked, we should selects only the first button when registering the click event. Right now the two buttons look pretty much the same; therefore, selecting with just button gives you both.
We can add more information to the DOM elements. Let's try that by example.
Let's add another button and change that first part of the page to:
<button id="button1" class="left-buttons">Click me!</button>
<button id="button2" class="left-buttons right-buttons">Don't click me</button>
<button id="button3" class="right-buttons">Don't ever click me</button>
Then try changing the selector "button" in the jQuery call to the following, and for each selector, try clicking the buttons to see which buttons can handle the click.
- "button1"
- "#button1"
- ".button1"
- "left-buttons"
- "#left-buttons"
- ".left-buttons"
Try to answer this:
- What selector should we use to select two buttons on the right?
- What selector should we use to select the first and the last buttons (not the middle one)? If you can't find a suitable selector, what should you do to register the click event to both of these buttons?
- What do . and # mean?
After you try the experiment and answer the above questions, you can see more explanation here.
id and class: A DOM element has two special attributes id and class. By definition, an ID should be unique for each element (i.e., you can't have two elements with the same ID). Many elements can share the same class; an element can also be in many classes. jQuery uses # to prefix the ID, and . to prefix the class in selectors. (This is a standard selector for CSS---a language that specifies page style.)
There are other ways to select elements, but this two selection should be enough for us for now.
Ready
As a common practice, we should work on the DOM elements after the web page is loaded. To do so, jQuery provides .ready function. It is a rather technical practice; right now, you can just remember how to do it.
Let's change the click registration of our code to
$(function(){ $("#button1").click(update); });
Note that we wrap our old code inside a function that is passed to function $. To see this, note the the above code is a compressed version of:
$( function(){ $("#button1").click(update); } );
The function passed to the $ function is defined without a name. We call it an anonymous function. This is a very useful feature of JavaScript.
As a quick summary, put all your jQuery registration and DOM-element modification in the wrapper like this:
$(function(){ // your code here });
- Let's commit at this point.
Modifying texts
Let's remove alert from our previous example. (And also remove useless buttons.) Change our page to this:
<!doctype html>
<html lang="en">
<body>
<span id="counterLabel">0</span><br>
<button id="counterButton">Click me!</button>
<script src="jquery.js"></script>
<script type="text/javascript">
var c = 0;
function update() {
c++;
$("#counterLabel").text('Counter = ' + c); // *****
}
$(function(){
$("#counterButton").click(update);
});
</script>
</body>
</html>
Try the page to see how it works.
- OK, here's the last commit.
A few questions to think about:
- Guess what .text(....) does?
- What happens at line *****?
- Do you see any automatic type conversion?
Let's write our game
Let's create a new directory guess and create a new Git repository in that directory. We shall re-write our number guessing game here.