Difference between revisions of "Introduction to JavaScript Fall 2010 Class 6"

esse quam videri
Jump to: navigation, search
m
m
 
Line 159: Line 159:
 
The function would work the same, no matter how you created it. Using an object to store your code is just the first step toward organizing your code in a
 
The function would work the same, no matter how you created it. Using an object to store your code is just the first step toward organizing your code in a
 
better way.
 
better way.
 +
 +
== Today's Interesting JavaScript Sites ==
 +
 +
Many JavaScript libraries are built to allow "plugins". Plugins extend a JavaScript library with new features that might not make sense for the main
 +
library, but could come in handy for some sites.
 +
 +
Below are a few examples of plugins for the jQuery library.
 +
 +
* [http://www.9lessons.info/2010/10/new-twitter-design-css-jquery.html New Twitter Interface jQuery plugin]
 +
* [http://webdev.stephband.info/parallax.html Parallax jQuery plugin]
 +
* [http://jqueryui.com/ jQueryUI]
 +
  
 
== Activity 1 ==
 
== Activity 1 ==

Latest revision as of 23:22, 12 October 2010

Back to Introduction to JavaScript Fall 2010

Introduction

This week we will talk about JavaScript objects. Objects are useful for a few different things. I will show you how you can store related information under a single variable, and how you can organize your code better by storing related functions inside of objects.

JavaScript Objects

One JavaScript feature that we haven't talked about is JavaScript Objects. jQuery uses JavaScript objects for a few functions, so you will need to understand them before taking of advantage of some of the functionality that jQuery provides.

Think of JavaScript objects as variables that contain other variables. Why would I want a variable that contained other variables? Sometimes, it's handy to group a set variables together under one variable. For example, let's say that I wanted to store some information about a person. I could create a variable for their first name, and their last name and their job title. Later on, I might want to create another variable for their hometown.

  var firstName = "Matt";
  var lastName = "Ephraim";
  var jobTitle = "Programmer";
  var hometown = "Cedar Falls";

So far, I've created 4 variables for that one person. What if, instead, I could create one variable that just stored all of the information about a person. I can do exactly that using a JavaScript object.

First, I need to create a new object. I can create a new object for a person like this:

  var person = {};

Think of the two empty curly brackets as two hands that will hold on to a collection of variables. If you say {} in your code, JavaScript will create a new object, ready for information to be stored in it. In the example above, a new object is being created and then stored in a variable called "person".

Note: Don't confuse the two curly brackets ({}) with 2 straight brackets ([]).

  • {} will create a new object
  • [] will create a new array.

Next, I want to store the person's information. Instead of creating a new variable for each piece of information, I can use the object like this:

  var person = {};
  person.firstName = "Matt";
  person.lastName = "Ephraim";
  person.jobTitle = "Programmer";
  person.hometown = "Cedar Falls";

Notice that, instead of creating a new variable, I'm using the person object instead. Every time I want to add a new piece of information I can say the name of the variable and then a dot (.) and then the name of piece of information I want to store. Later on, I can get the piece of information back by using the same name that I used when I set the piece of information, like this:

  alert(person.firstName); // alerts "Matt"
  alert(person.lastName); // alerts "Ephraim"
  alert(person.jobTitle); // alerts "Programmer"
  alert(person.hometown); // alerts "Cedar Falls"

Similar to how you can think of the curly brackets as hands, think of the dot has a hole that lets you look inside of the object to get something out of it. So, when you say "Lock.reset()", you're using the dot to look inside of the Lock object to find the reset function.

There's also a way to shorten this process I little bit. If I wanted to, I could have also set all of the pieces of information at the same time that I was creating the variable, like this:

  var person = {
      firstName: "Matt",
      lastName: "Ephraim",
      jobTitle: "Programmer",
      hometown: "Cedar Falls"
  };

This piece of code does the exact same thing as creating the variable and setting each one of those pieces of information. The only difference is that each item is set inside of the brackets. To create a new item (or property) I can add the name of the property, followed by a colon (:) and then the value of the property in quotes. Each property has to be separated by a comma and a property has to be inside of the brackets.

You can still think of the curly brackets as hands, but in this case, the hands are holding onto a collection of values right away

Remember jQuery's animate function? The animate function takes in an object that represents the CSS values you'd like to set for the element that you're animating:

 var element = $("#my_element");
 element.animate({ width: "100px", height: "300px" }, 100);

In the example above, an object is being passed in that will set the width of the element to 100 pixels and the height of the element to 300 pixels.

Using Obects to Organize Your Code

Objects can be used to store all kinds of information, including strings, numbers and even functions. A few weeks ago, we created a combination lock that had a variable for a combination, a variable that deterimined if the lock was unlocked or not and some functions that made the lock actually work. The code we wrote worked fine, but if we would have written more code, it might have gotten a little bit confusing. What if we needed a few different variables called COMBINATION, or what if we needed 2 functions called reset? Both of these issues could be addressed by storing the code related to the lock in an object, instead of just using regular variables.

To start organizing the code, we need to create a new object to store all of the functions and variables related to the lock. Let's call the object Lock:

  var Lock = {};

Lock is now an empty object, ready to have properties stored on it. To start with, we can store the lock's combination as a propery of the Lock object:

  var Lock = {};
  Lock.COMBINATION = '111';

Later, the lock's combination can be referenced like so:

  alert(Lock.COMBINATION);

We can also stored the unlocked variable as a property on the lock, as well:

  Lock.unlocked = false;

Later, the value can be changed or checked:

  if(Lock.unlocked) {
    // do something
  }
  
  Lock.unlocked = true;

Now that we have the variables stored as properties on the Lock object, instead of just as regular variables, we could have other objects that had COMBINATION or unlocked properies and use them somewhere else in our code:

  var BikeLock = {};
  BikeLock.COMBINATION = "5555";
  BikeLock.unlocked = false;
  
  if (BikeLock.unlocked) {
    // ride the bike
  }

One thing that I haven't talked about yet is how you can save functions as variables or as properties. So far, the way we've created functions has looked like this:

  function reset() {
    // some code to reset the lock
  }

JavaScript also lets you create functions like this:

 var reset = function() {
   // some code to reset the lock
 };

Notice that we are now creating a variable called reset and storing a function in the variable. Instead of giving the function a name right away, you can leave the name off of the function and create a variable that stores the function instead. For the most part, both ways of creating the function will work the same. Whichever way you use, you always be able to call the function like this:

  reset();

Additionally, you can store a function in an object. Just like you can store a regular variable on an object. Storing the reset function on the Lock object looks like this:

  Lock.reset = function() {
    // some code to reset the lock
  }

Later, to call the function, you would say:

  Lock.reset();

The function would work the same, no matter how you created it. Using an object to store your code is just the first step toward organizing your code in a better way.

Today's Interesting JavaScript Sites

Many JavaScript libraries are built to allow "plugins". Plugins extend a JavaScript library with new features that might not make sense for the main library, but could come in handy for some sites.

Below are a few examples of plugins for the jQuery library.


Activity 1

The first activity today involves the same lock game that we worked on during Class 4. You can find completed version of the game here.

For this activity we will be organizing our code a bit by keeping all of our functions and variables as properties of an object. We will call this object Lock. You can get started by creating a Lock object at the beginning of your code:

  var Lock = {};

Then, once you have the empty object, you can start adding variables and functions to it:

  // Store the combination on the lock
  Lock.COMBINATION = "111";
  
  // Store the reset function
  Lock.reset = function() {
    // code for the reset function
  }
  

You should only need to store variables that might be useful for all of your functions on the Lock object. If you're creating a variable inside of a function, don't worry about storing it on the Lock object. Just focus on variables like COMBINATION and unlocked that are declared outside of functions.


Activity 2

For this activity we're going to continue to rewrite the code for the lock using jQuery.

I will walk you through each step and how you how jQuery can make things a little more streamlined.

A few things to think about:

  • Selectors

Remember that you can use jQuery's selectors to find the elements, instead of just finding them by their id. For example, you can find all of the number boxes by using their class name. So a jQuery selector for all of the number boxes would look something like this:

  var numbers = jQuery('.number');

You can then attach event handlers or modify styles using the numbers variable, which represents a collection of all of the number boxes that were found.

  • Adding classes

You can add classes or remove classes for an element by using the addClass and removeClass functions:

  var element = jQuery('#id');
  element.addClass('highlighted');
  element.removeClass('highlighted');

Assignment 3

Remember that assignment 3 is due this Friday, October 15th