75
Computer Science and Engineering n The Ohio State University To Ponder Assume: var d = new Dog(); d instanceof Dog; //#=> true d instanceof Pet; //#=> true Questions: n What is Dog? (A class? An interface? ...) n What is Pet? n How are they related? Draw the hierarchy

To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

To Ponder

Assume:var d = new Dog();d instanceof Dog; //#=> trued instanceof Pet; //#=> true

Questions:n What is Dog? (A class? An interface? ...)n What is Pet?n How are they related? Draw the hierarchy

Page 2: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

To Ponder

Page 3: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n College of Engineering n The Ohio State University

JavaScript:Objects, Methods, Prototypes

Lecture 15

Page 4: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

What is an Object?o Property: a key/value pair (aka “name”

/value)o Object: a partial map of properties

n Keys must be uniqueo Creating an object, literal notation

var myCar = { make: "Acura",year: 1996,plate: "NKR462" };

o To access/modify an object's properties:myCar.make = "Ford"; //cf. RubymyCar["year"] = 2006;var str = "ate";myCar["pl" + str] == "NKR463";

Page 5: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Object Properties

"Ford"

2006

"NKR463"

make

year

plate

myCar

Page 6: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Arrays vs Associative Arrays

4

"hi"

3.14 true

true

false

0

1

2

0

1

2

3

4

"hi"

3.14 true

true

false

0

1

2

age

greeting

doors

pi

Page 7: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Dynamic Size, Just Like Arrays

o Objects can growmyCar.state = "OH"; // 4 propertiesvar myBus = {}; myBus.driver = true; // adds a propmyBus.windows = [2, 2, 2, 2];

o Objects can shrinkdelete myCar.plate;// myCar is now {make: "Ford",// year: 2006, state: "OH"}

Page 8: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Object Properties

"Ford"

2006

"NKR463"

make

year

plate

myCar

Page 9: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Object Properties

"Ford"

2006

"NKR463"

"OH"

make

year

plate

state

myCar myCar.state = "OH";

Page 10: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Object Properties

"Ford"

2006

"OH"

make

year

state

myCar delete myCar.plate;

Page 11: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Testing Presence of Key

o Boolean operator: inpropertyName in object

o Evaluates to true iff object has the indicated property key

"make" in myCar //=> true"speedometer" in myCar //=> false"OH" in myCar //=> false

n Property names are strings

Page 12: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Iterating Over Properties

o Iterate using for…in syntaxfor (property in object) {

…object[property]…}

o Notice [] to access each propertyfor (p in myCar) {

document.write(p +": " + myCar[p]);}

Page 13: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Methodso The value of a property can be:

n A primitive (boolean, number, string, null…)n A reference (object, array, function)

var temp = function(sound) {play(sound);return 0;

}myCar.honk = temp;

o More succinctly:myCar.honk = function(sound) {play(sound);return 0;

}

Page 14: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Example: Method

var myCar = {make: "Acura",year: 1996,plate: "NKR462",honk: function(sound) {

play(sound);return 0;

}};

Page 15: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Object Properties

"Acura"

1996

"NKR462"

make

year

plate

honkplay(sound);return 0;

myCar

Page 16: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Keyword “this” in Functionso Recall distinguished formal parameter

x.f(y, z); //x is the distinguished argmt.o Inside a function, keyword “this”

function report() {return this.plate + this.year;

}o At run-time, “this” is set to the distinguished

argument of invocationmyCar = {plate: "NKR462", year: 1996};yourCar = {plate: 340, year: 2013};myCar.register = report;yourCar.info = report;myCar.register(); //=> "NKR4621996"yourCar.info(); //=> 2353

Page 17: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Object Properties

"NKR462"

1996

plate

year

register

return this.plate + this.year;

myCar

report

340

2013

plate

year

info

yourCar

Page 18: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Constructorso Any function can be a constructoro When calling a function with “new”:

1. Make a brand new (empty) object2. Call the function, with the new object as the

distinguished parameter3. Implicitly return the new object to caller

o A “constructor” often adds properties to the new object simply by assigning them

function Dog(name) {this.name = name; // adds 1 property// no explicit return

}var furBall = new Dog("Rex");

o Naming convention: Functions intended to be constructors are capitalized

Page 19: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Examplefunction Circle(x, y, radius) { this.centerX = x; this.centerY = y; this.radius = radius; this.area = function() {return Math.PI * this.radius *

this.radius; }

}var c = new Circle(10, 12, 2.45);

Page 20: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Creating a Circle Object

var c = new Circle(10, 12, 2.45);

this.centerX = x;this.centerY = y;... Etc ...

Circle

Page 21: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Creating a Circle Object

var c = new Circle(10, 12, 2.45);

this.centerX = x;this.centerY = y;... Etc ...

Circle

Page 22: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Creating a Circle Object

10

12

2.45

centerX

centerY

radius

return Math.PI * this.radius * this.radius

area

var c = new Circle(10, 12, 2.45);

this.centerX = x;this.centerY = y;... Etc ...

Circle

Page 23: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Creating a Circle Object

10

12

2.45

centerX

centerY

radius

return Math.PI * this.radius * this.radius

c

area

var c = new Circle(10, 12, 2.45);

this.centerX = x;this.centerY = y;... Etc ...

Circle

Page 24: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Creating a Circle Object

10

12

2.45

centerX

centerY

radius

return Math.PI * this.radius * this.radius

c

area

var c = new Circle(10, 12, 2.45);

this.centerX = x;this.centerY = y;... Etc ...

Circle

Page 25: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Prototypes

o Every object has a prototypen A hidden, indirect property ([[Prototype]])

o What is a prototype?n Just another object! Like any other!

o When accessing a property (i.e. obj.p)n First look for p in objn If not found, look for p in obj's prototypen If not found, look for p in that object's

prototype!n And so on, until reaching the basic system

object

Page 26: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Prototype Chaining

4"hi"

3.14

true

true

false

0

1

2

agegreeting

doors

pi

toString

hasOwnProperty

push

pop

etc…

Page 27: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Class-Based Inheritance

static static static

interfaces

classes

objects

extends

extends

implements

instantiates

Page 28: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Example

o Consider two objectsvar dog = {name: "Rex", age: 3};var pet = {color: "blue"};

o Assume pet is dog's prototype// dog.name is "Rex" // dog.color is "blue" (follow chain) pet.color = "brown"; // dog.color is "brown" (prop changed)dog.color = "green"; // pet.color is still "brown" (hiding)

Page 29: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Delegation to Prototype

"brown""Rex"

3

colorname

age

"green"color

dog pet

Page 30: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Prototypes Are Dynamic Too

o Prototypes can add/remove propertieso Changes are felt by all children

// dog is {name: "Rex", age: 3}// dog.mood & pet.mood are undefinedpet.mood = "happy"; // add to pet// dog.mood is now "happy" toopet.bark = function() {return this.name + " is " + this.mood;

}dog.bark(); //=> "Rex is happy"pet.bark(); //=> "undefined is happy"

Page 31: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Delegation to Prototype

"brown""Rex"

3

colorname

age

dog pet

"happy"mood

barkreturn this.name

+ " is "+ this.mood;

dog.bark();pet.bark();

Page 32: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Connecting Objects & Prototypes

o How does an object get a prototype?var c = new Circle();

o Answer1. Every function has a prototype property

o Do not confuse with hidden [[Prototype]]!2. Object's prototype link—[[Prototype]]—

is set to the function's prototype propertyo When a function Foo is used as a

constructor, i.e. new Foo(), the value of Foo's prototype property is the prototype object of the created object

Page 33: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Prototypes And Constructors

area

constructor

prototype

this.centerX = x;this.centerY = y;... Etc ...

Circle

Page 34: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Prototypes And Constructors

area

constructor

prototype

this.centerX = x;this.centerY = y;... Etc ...

Circle

c = new Circle()

Page 35: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Prototypes And Constructors

area

constructor

prototype

this.centerX = x;this.centerY = y;... Etc ...

Circle

c = new Circle()

Page 36: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Prototypes And Constructors

10

12

2.45

centerX

centerY

radius

area

constructor

prototype

this.centerX = x;this.centerY = y;... Etc ...

c

Circle

c = new Circle()

Page 37: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Idiom: Methods in Prototypefunction Dog(n, a) {

this.name = n; this.age = a;

};

var canine = { bark: function (sound) {

return this.name + "says" + sound; }

};

Dog.prototype = canine;

Page 38: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Idiom: Methods in Prototypefunction Dog(n, a) {

this.name = n; this.age = a;

};

var canine = { bark: function (sound) {

return this.name + "says" + sound; }

};

Dog.prototype = canine;

Page 39: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Idiom: Methods in Prototypefunction Dog(n, a) {

this.name = n; this.age = a;

};

Dog.prototype = { bark: function (sound) {

return this.name + "says" + sound; }

}; // set prototype to new anonymous object

Page 40: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Idiom: Methods in Prototypefunction Dog(n, a) {

this.name = n; this.age = a;

};

Dog.prototype.bark = function (sound) { return this.name + "says" + sound;

};

// better: extend existing prototype

Page 41: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Methods in Prototype

"Rex"

6

name

age

bark

constructor

prototype

this.name = x;this.age = a;

Dog

return this.name+ "says" + sound;

prototype

r = new Dog() Dog.prototype

Page 42: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Idiom: Classical Inheritancefunction Animal() { ... };function Dog() { ... };

Dog.prototype = new Animal();// create prototype for future dogs

Dog.prototype.constructor = Dog;// set prototype's constructor// properly (ie should point to Dog())

Page 43: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Setting up Prototype Chains

constructor

prototype

Animal

constructor

prototype

Dog

new Animal()

"Rex"name

new Dog()

Page 44: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Summary

o Objects as associative arraysn Partial maps from keys to valuesn Can dynamically add/remove propertiesn Can iterate over properties

o Method = function-valued propertyn Keyword this for distinguished parameter

o Constructor = any functiono Prototypes are "parent" objects

n Delegation up the chain of prototypesn Prototype is determined by constructorn Prototypes can be modified

Page 45: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n College of Engineering n The Ohio State University

JavaScript:DOM and Events

Page 46: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Objects are Everywhere

o Global variables in JavaScript are a lieo Implicitly part of some "global object",

provided by execution environmentn See FF Developer Tools: Console

Page 47: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Window Object

o For JavaScript running in a browser, implicit global object is the window>> this<- Window

o Many properties, includingn location (url of displayed document)n status (text in status bar of browser)n historyn innerHeight, innerWidthn alert(), prompt()n document (tree of displayed document)

Page 48: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Document is a Tree

htmllang: en

head body

title metacharset: utf-8

p

ahref: planet.html

Something Short and Sweet

Hello

elementattr name:attr valuetext

World

! br imgsrc: pic.pngalt: a globe

Page 49: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

DOM: "Document Object Model"o DOM is a language-neutral API for

working with HTML (and XML) documentsn Different programming languages have

different bindings to this API n But all are similar to JavaScript's API

o In JavaScript, tree nodes à objectsn A tree node (i.e. an element with attributes)

<input type="text" name="address"> n A JavaScript object with many properties

{ tagName: "INPUT",type: "text",name: "address", /*lots more…*/ }

Page 50: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

DOM Historyo Ad hoc DOM existed from the beginning of

JavaScriptn Core purpose of client-side execution: Enable user

interaction with the documentn Need a connection between programming language

(JavaScript) and the documento DOM 1 specification (W3C) in '98

n Standardized mapping treeàobjects and functions for modifying the tree

o DOM 2 ('00): added styles and event handling o DOM 3 ('04): fancier tree traversal & indexing

schemeso DOM "4" ('15…):

n Actually just a "living document"n Some non-backwards-compatible changes

Page 51: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Simplest Mapping

o windown document

o write(): outputs text to document bodyo forms: array of forms in a page

n elements[]: array of widgets in a formo anchors: all anchors in documento links: all links in documento getElementById(string): find a nodeo etc…

Page 52: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Document is a Tree

htmllang: en

head body

title metacharset: utf-8

p

ahref: planet.html

Something Short and Sweet

Hello

elementattr name:attr valuetext

World

! br imgsrc: pic.pngalt: a globe

Page 53: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Node is a JavaScript Objecto Properties

n parentNode, childNodes, firstChild, lastChild, nextSibling, previousSibling

n innerHTMLn tagName

o XML lower case ("a"), HTML upper case ("A")n attributes, name, id, classn style

o Hyphenated property in CSS (e.g., “font-size”) becomes camelCase in JavaScript (e.g., “fontSize”)

o Methodsn appendChild(node), removeChild(node),

insertBefore(node)n hasAttribute(attr), removeAttribute(attr),

getAttribute(attr), setAttribute(attr)n getElementsByTagName(name)

Page 54: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Demo: Web Console>> var b = document.body;>> b.tagName;>> b.childNodes;>> b.style.backgroundColor = "green";>> >> var x = document.getElementById

("page-content");>> x.innerHTML;>> x.innerHTML = "<h1>Hello</h1>";

Page 55: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

How to Find a Node in Tree1. Hard coding with "flat" techniques

n Array of childrendocument.forms[0].elements[0]

n Downside: too brittlen If the document structure changes a little,

everything breaks2. Using an element's name attribute

n In HTML:<form name="address"> … <input name="zip"... /> </form>

n In JavaScript:document.address.zip

n Downside: direct path still hard coded

Page 56: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

How to Find a Node in Tree

3. To get a unique element: document method getElementByIdn In HTML

<td id="shipping">...</td>

n In JavaScriptdocument.getElementById("shipping")

n Downside: every element you want to find needs unique ID

4. Combination: element ID for form, arrays for options in selection element

Page 57: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Example<form id="wheels">

<input type="checkbox" name="vehicles"value="car" /> Car

<input type="checkbox" name="vehicles"value="truck" /> Truck

<input type="checkbox" name="vehicles"value="bike" /> Bike

</form>

var numChecked = 0;var elt = document.getElementById("wheels");for (i = 0; i < elt.vehicles.length; i++) {

if (elt.vehicles[i].checked)numChecked++;

}

Page 58: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Interactive Documents

o To make a document interactive, you need:n Widgets (ie HTML elements)

o Buttons, windows, menus, etc.n Events

o Mouse clicked, window closed, button clicked, etc.

n Event listenerso Listen (ie wait) for events to be triggered,

and then perform actions to handle them

Page 59: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Events Drive the Flow of Control

o This style is event driven programmingo Event handling occurs as a loop:

n Program is idlen User performs an action

o Eg moves the mouse, clicks a button, types in a text box, selects an item from menu, …

n This action generates an event (object)n That event is sent to the program, which

respondso Code executes, could update document

n Program returns to being idle

Page 60: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Handling Events Mechanismo Three parts of the event-handling

mechanismn Event source: the widget with which the user

interactsn Event object: encapsulated information about the

occurred eventn Event listener: a function that is called when an

event occurs, and responds to the event

HTML Element aHandler()event object

Page 61: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Programmer Tasks

o Define an event handlern Any function can be an event handlern Often need information about the

triggering event in order to know what response is needed

o Register handler with source elemento Detect event and invoke handler

n Ha! Just kidding, you do NOT do this

Page 62: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Simple Example: Color Swaps<p>This page illustrates changing colors</p><form><p><label> background: <input type="text" name="back" size="10"onchange="foo('bg', this.value)" />

</label> <br /><label> foreground:<input type="text" name="fore" size="10"onchange="foo('fg', this.value)" />

</label> </p>

</form>

Page 63: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Color Swaps (JavaScript)function foo(place, color) {if (place === "bg") document.body.style.backgroundColor =

color;else document.body.style.color = color;

}

Page 64: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Event Propagation

o Elements are nested in treeo When an event occurs, which

element's handler(s) is(are) notified?o First, propagation path is calculated:

from root to smallest elemento Then event dispatch occurs in 3 phases

1. Capture (going down the path)2. Target (smallest element)3. Bubble (going up the path, reverse of 1)

Page 65: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

http://www.w3.org/TR/DOM-Level-3-Events/

Page 66: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Bubbling Up

o Usually, handling is done in phase 2 and 3

o Example: mouse click on hyperlinkn Handler for <a> element displays a pop-

up ("Are you sure you want to leave?")n Once that is dismissed, event flows up to

enclosing <p> element, then <div> then… etc. until it arrives at root element of DOM

n This root element (i.e. window) has a handler that loads the new document in the current window

Page 67: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Programmer Tasks

o Define a handlern Easy, any function will do

o Register handlern Multiple ways to link (HTML) tree elements

with (JavaScript) functionso Be triggered by the event

n Ha! Still kiddingo Get information about triggering event

n Multiple (incompatible) ways for handler to get the event object

Page 68: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Registering an Event Handlero Three techniques, ordered from:

n Oldest (most brittle, most universal) ton Newest (most general, least standard)

1. Inline (link in HTML itself)<a href="page.html" onclick="foo()">…

2. Direct (link in JavaScript)var e = … //find source element in treee.onclick = foo;

3. Chained (In JavaScript, browser differences)var e = … //find source element in treee.addEventListener("click", foo, false);

Page 69: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Inline Registration (pre DOM)o Use HTML attributes (vary by element type)

n For window: onload, onresize, onunload,…n Forms & elements: onchange, onblur, onfocus,

onsubmit,…n Mouse events: onclick, onmouseover,

onmouseout,…n Keyboard events: onkeypress, onkeyup,…

o The value of these attributes is JavaScript code to be executedn Normally just a function invocation

o Example<a href="page.html" onclick="foo()">…

o Advantage: Quick, easy, universalo Disadvantage: mixes code with content

Page 70: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Direct Registration (DOM 1)o Use properties of DOM element objects

n onchange, onblur, onfocus,…n onclick, onmouseover, onmouseout,…n onkeypress, onkeyup,…

o Set this property to appropriate handlervar e = … // find source element in treee.onclick = foo;

o Note: no parentheses!e.onclick() = foo; // what does this do?e.onclick = foo(); // what does this do?

o Disadvantage? No arguments to handlern Not a problem, handler gets event object

o Real disadvantage: 1 handler/element

Page 71: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Examplevar x = document.getElementsByTagName("div");for (var i = 0; i < x.length; i++) {x[i].onmouseover = function () {this.style.backgroundColor="red"

}x[i].onmouseout = function () {this.style.backgroundColor="blue"

}}

Page 72: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Chained Registration (DOM 2)o Each element has a collection of handlerso Add/remove handler to this collection

var e = … //find source element in treee.addEventListener("click", foo, false);

o Note: no "on" in event names, just "click"o Third parameter: true for capture phaseo Disadvantage: browser incompatibilities

e.addEventListener() // FF, Webkit, IE9+e.attachEvent() // IE5-8

o Many browser compatibility issues with DOM and events

o Solution: Librariesn Eg jQuery, Dojo, Prototype, YUI, MooTools,…

Page 73: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Examplevar x = document.getElementsByTagName("div");for (var i = 0; i < x.length; i++) {

x[i].addEventListener ("click",function () {

this.act = this.act || false;this.act = !this.act;this.style.backgroundColor =(this.act ? "red" : "gray");

},false);

}

Page 74: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Task: Getting Event Object

o Most browsers: parameter to handlerfunction myHandler(event)

o IE: event is property of windowo Common old-school idiom:

function myHandler(event) {event = event || window.event;… etc …

o Again, libraries are the most robust way to deal with these issues

Page 75: To Ponderweb.cse.ohio-state.edu/~giles.25/3901/lectures/lecture15.pdf · 2019-10-03 · Computer Science and Engineering nThe Ohio State University Constructors oAnyfunction can be

Computer Science and Engineering n The Ohio State University

Summary

o DOM: Document Object Modeln Programmatic way to use document treen Get, create, delete, and modify nodes

o Event-driven programmingn Source: element in HTML (a node in DOM)n Handler: JavaScript functionn Registration: in-line, direct, chainedn Event is available to handler for inspection