250
Using JavaScript DOM BOM jQuery AJAX Long Polling WebSocket Knockout Using JavaScript for Client-Side Behavior Internet Applications, ID1354 1 / 93

Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

  • Upload
    others

  • View
    16

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Using JavaScript for Client-SideBehavior

Internet Applications, ID1354

1 / 93

Page 2: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Contents

The Document Object Model, DOM

The Browser Object Model, BOM

The jQuery JavaScript Library

AJAX

Long Polling

WebSocket

The Knockout JavaScript Framework

2 / 93

Page 3: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Section

The Document Object Model, DOM

The Browser Object Model, BOM

The jQuery JavaScript Library

AJAX

Long Polling

WebSocket

The Knockout JavaScript Framework

3 / 93

Page 4: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Document Object Model, DOM

I The W3C Document Object Model, DOM, isan API that allows programs to access andupdate document content.

I Defines objects representing HTMLelements, methods to access HTMLelements, and events generated by HTMLelements.

I The best that can be said about browsersupport is that it varies.

I Try the features you want to use in all relevantbrowsers, check caniuse.com, etc

4 / 93

Page 5: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Document Object Model, DOM

I The W3C Document Object Model, DOM, isan API that allows programs to access andupdate document content.

I Defines objects representing HTMLelements, methods to access HTMLelements, and events generated by HTMLelements.

I The best that can be said about browsersupport is that it varies.

I Try the features you want to use in all relevantbrowsers, check caniuse.com, etc

4 / 93

Page 6: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Document Object Model, DOM

I The W3C Document Object Model, DOM, isan API that allows programs to access andupdate document content.

I Defines objects representing HTMLelements, methods to access HTMLelements, and events generated by HTMLelements.

I The best that can be said about browsersupport is that it varies.

I Try the features you want to use in all relevantbrowsers, check caniuse.com, etc

4 / 93

Page 7: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Document Object Model, DOM

I The W3C Document Object Model, DOM, isan API that allows programs to access andupdate document content.

I Defines objects representing HTMLelements, methods to access HTMLelements, and events generated by HTMLelements.

I The best that can be said about browsersupport is that it varies.

I Try the features you want to use in all relevantbrowsers, check caniuse.com, etc

4 / 93

Page 8: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The DOM Tree

I The DOM objects are organizedin a tree.

I The picture to the left is a part ofthe DOM tree for the course’schat program.

5 / 93

Page 9: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The DOM Tree

I The DOM objects are organizedin a tree.

I The picture to the left is a part ofthe DOM tree for the course’schat program.

5 / 93

Page 10: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The DOM JavaScript APII All HTML elements are represented by

objects.I The HTML objects have properties you can

get or set, to read or update the objects.

I The HTML objects have methods, forexample for adding and deleting elements.

I An example is the JavaScript statementdocument.getElementById("demo").innerHTML =

"Hello World!";

that uses the method getElementByIdto find the HTML object for the element withid demo, and sets the HTML of that objectto "Hello World!", using theinnerHTML property.

6 / 93

Page 11: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The DOM JavaScript APII All HTML elements are represented by

objects.I The HTML objects have properties you can

get or set, to read or update the objects.I The HTML objects have methods, for

example for adding and deleting elements.

I An example is the JavaScript statementdocument.getElementById("demo").innerHTML =

"Hello World!";

that uses the method getElementByIdto find the HTML object for the element withid demo, and sets the HTML of that objectto "Hello World!", using theinnerHTML property.

6 / 93

Page 12: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The DOM JavaScript APII All HTML elements are represented by

objects.I The HTML objects have properties you can

get or set, to read or update the objects.I The HTML objects have methods, for

example for adding and deleting elements.I An example is the JavaScript statement

document.getElementById("demo").innerHTML ="Hello World!";

that uses the method getElementByIdto find the HTML object for the element withid demo, and sets the HTML of that objectto "Hello World!", using theinnerHTML property.

6 / 93

Page 13: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The DOM JavaScript APII All HTML elements are represented by

objects.I The HTML objects have properties you can

get or set, to read or update the objects.I The HTML objects have methods, for

example for adding and deleting elements.I An example is the JavaScript statement

document.getElementById("demo").innerHTML ="Hello World!";

that uses the method getElementByIdto find the HTML object for the element withid demo, and sets the HTML of that objectto "Hello World!", using theinnerHTML property.

6 / 93

Page 14: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The document Object

I The object document can be accessed byany JavaScript code. It represents theentire web page and is the entry point tothe DOM API.

I Sample methods in document areFind HTML elements getElementById,

getElementsByTagName,getElementsByClassName

Properties of HTML elements innerHTML, attributesAdd or delete elements createElement,

removeChild, appendChildCollections of HTML elements cookie, URL, elements,

forms

7 / 93

Page 15: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The document Object

I The object document can be accessed byany JavaScript code. It represents theentire web page and is the entry point tothe DOM API.

I Sample methods in document areFind HTML elements getElementById,

getElementsByTagName,getElementsByClassName

Properties of HTML elements innerHTML, attributes

Add or delete elements createElement,removeChild, appendChild

Collections of HTML elements cookie, URL, elements,forms

7 / 93

Page 16: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The document Object

I The object document can be accessed byany JavaScript code. It represents theentire web page and is the entry point tothe DOM API.

I Sample methods in document areFind HTML elements getElementById,

getElementsByTagName,getElementsByClassName

Properties of HTML elements innerHTML, attributesAdd or delete elements createElement,

removeChild, appendChild

Collections of HTML elements cookie, URL, elements,forms

7 / 93

Page 17: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The document Object

I The object document can be accessed byany JavaScript code. It represents theentire web page and is the entry point tothe DOM API.

I Sample methods in document areFind HTML elements getElementById,

getElementsByTagName,getElementsByClassName

Properties of HTML elements innerHTML, attributesAdd or delete elements createElement,

removeChild, appendChildCollections of HTML elements cookie, URL, elements,

forms

7 / 93

Page 18: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The document Object

I The object document can be accessed byany JavaScript code. It represents theentire web page and is the entry point tothe DOM API.

I Sample methods in document areFind HTML elements getElementById,

getElementsByTagName,getElementsByClassName

Properties of HTML elements innerHTML, attributesAdd or delete elements createElement,

removeChild, appendChildCollections of HTML elements cookie, URL, elements,

forms

7 / 93

Page 19: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Change CSS Rules

I To change CSS rules use the following typeof statement:document.getElementById(id).style.<property>

= <some style>

I For example, the statementdocument.getElementById("p2").style.color =

"blue";

changes the font color of element with idp2 to blue.

8 / 93

Page 20: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Change CSS Rules

I To change CSS rules use the following typeof statement:document.getElementById(id).style.<property>

= <some style>

I For example, the statementdocument.getElementById("p2").style.color =

"blue";

changes the font color of element with idp2 to blue.

8 / 93

Page 21: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

EventsI The DOM defines many events, for

example onClick, which is fired by anelement when the user clicks on it.

I To react to an event, add JavaScript code tothe event handler attribute of the elementthat generates the event.

I For example, to change text in theparagraph when the user clicks it:<p onclick="clicked(this)">Click Me!</p>

function clicked(source) {source.innerHTML = "You clicked";

}

9 / 93

Page 22: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

EventsI The DOM defines many events, for

example onClick, which is fired by anelement when the user clicks on it.

I To react to an event, add JavaScript code tothe event handler attribute of the elementthat generates the event.

I For example, to change text in theparagraph when the user clicks it:<p onclick="clicked(this)">Click Me!</p>

function clicked(source) {source.innerHTML = "You clicked";

}

9 / 93

Page 23: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

EventsI The DOM defines many events, for

example onClick, which is fired by anelement when the user clicks on it.

I To react to an event, add JavaScript code tothe event handler attribute of the elementthat generates the event.

I For example, to change text in theparagraph when the user clicks it:<p onclick="clicked(this)">Click Me!</p>

function clicked(source) {source.innerHTML = "You clicked";

}

9 / 93

Page 24: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Examples of Events

Mouse events onclick, ondblclick,onmousedown, onmouseover

Keyboard events onkeydown, onkeypress,onkeyup, fired in that order.

Object events onload, onunloadForm events onchange, onselect

10 / 93

Page 25: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Examples of Events

Mouse events onclick, ondblclick,onmousedown, onmouseover

Keyboard events onkeydown, onkeypress,onkeyup, fired in that order.

Object events onload, onunload

Form events onchange, onselect

10 / 93

Page 26: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Examples of Events

Mouse events onclick, ondblclick,onmousedown, onmouseover

Keyboard events onkeydown, onkeypress,onkeyup, fired in that order.

Object events onload, onunloadForm events onchange, onselect

10 / 93

Page 27: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Examples of Events

Mouse events onclick, ondblclick,onmousedown, onmouseover

Keyboard events onkeydown, onkeypress,onkeyup, fired in that order.

Object events onload, onunloadForm events onchange, onselect

10 / 93

Page 28: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Event ListenersI The JavaScript function addEventListener()

attaches an event listener to the specified element.<button id="myBtn">Try it</button><p id="demo"></p>

document.getElementById("myBtn").addEventListener("click", displayDate);

function displayDate() {document.getElementById("demo").

innerHTML = Date();}

I Multiple event listeners, even of the same type, canbe attached to the same element.

I Event listeners is preferred over onEventattributes since it separates JavaScript from HTML,thereby increasing cohesion.

11 / 93

Page 29: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Event ListenersI The JavaScript function addEventListener()

attaches an event listener to the specified element.<button id="myBtn">Try it</button><p id="demo"></p>

document.getElementById("myBtn").addEventListener("click", displayDate);

function displayDate() {document.getElementById("demo").

innerHTML = Date();}

I Multiple event listeners, even of the same type, canbe attached to the same element.

I Event listeners is preferred over onEventattributes since it separates JavaScript from HTML,thereby increasing cohesion. 11 / 93

Page 30: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Event ListenersI The JavaScript function addEventListener()

attaches an event listener to the specified element.<button id="myBtn">Try it</button><p id="demo"></p>

document.getElementById("myBtn").addEventListener("click", displayDate);

function displayDate() {document.getElementById("demo").

innerHTML = Date();}

I Multiple event listeners, even of the same type, canbe attached to the same element.

I Event listeners is preferred over onEventattributes since it separates JavaScript from HTML,thereby increasing cohesion. 11 / 93

Page 31: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Passing Parameters to EventListeners

I The following code illustrates how to passparameters to event listeners.

<button id="myBtn">Try it</button><p id="demo"></p>

document.getElementById("myBtn").addEventListener("click", function() {

showLabel(this);});

function showLabel(source) {document.getElementById("demo").innerHTML

= source.innerHTML;}

12 / 93

Page 32: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Question 1

13 / 93

Page 33: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Event Bubbling

I When an element fires an event, also theevent handlers of its parents are invoked.

I An event first triggers the deepest possibleelement, then its parents in nesting order.

14 / 93

Page 34: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Event Bubbling

I When an element fires an event, also theevent handlers of its parents are invoked.

I An event first triggers the deepest possibleelement, then its parents in nesting order.

14 / 93

Page 35: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Event Bubbling ExampleI HTML:

<div onclick="show(1)">1<div onclick="show(2)">2

<div onclick="show(3)">3<p id="event-log"></p>

</div></div>

</div>

JavaScript:function show(sourceNo) {

var curr = document.getElementById("event-log").innerHTML;

document.getElementById("event-log").innerHTML = curr + " " + sourceNo;

}

I When clicking the innermost div (number3), the output is 3 2 1 15 / 93

Page 36: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Event Bubbling ExampleI HTML:

<div onclick="show(1)">1<div onclick="show(2)">2

<div onclick="show(3)">3<p id="event-log"></p>

</div></div>

</div>

JavaScript:function show(sourceNo) {

var curr = document.getElementById("event-log").innerHTML;

document.getElementById("event-log").innerHTML = curr + " " + sourceNo;

}

I When clicking the innermost div (number3), the output is 3 2 1 15 / 93

Page 37: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Stopping the BubblingI Bubbling is prevented by callingstopPropagation() on the event object.

I <div onclick="show(1)">1<div onclick="show(2)">2

<div onclick=’show(3, event)’>3<p id="log"></p>

</div></div>

</div>

function show(sourceNo, event) {var curr = document.

getElementById("log").innerHTML;document.getElementById("log").

innerHTML = curr + " " + sourceNo;event.stopPropagation();

}

I When clicking the innermost div, output is now 3

16 / 93

Page 38: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Stopping the BubblingI Bubbling is prevented by callingstopPropagation() on the event object.

I <div onclick="show(1)">1<div onclick="show(2)">2

<div onclick=’show(3, event)’>3<p id="log"></p>

</div></div>

</div>

function show(sourceNo, event) {var curr = document.

getElementById("log").innerHTML;document.getElementById("log").

innerHTML = curr + " " + sourceNo;event.stopPropagation();

}

I When clicking the innermost div, output is now 3 16 / 93

Page 39: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Stopping the BubblingI Bubbling is prevented by callingstopPropagation() on the event object.

I <div onclick="show(1)">1<div onclick="show(2)">2

<div onclick=’show(3, event)’>3<p id="log"></p>

</div></div>

</div>

function show(sourceNo, event) {var curr = document.

getElementById("log").innerHTML;document.getElementById("log").

innerHTML = curr + " " + sourceNo;event.stopPropagation();

}

I When clicking the innermost div, output is now 3 16 / 93

Page 40: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Event Capturing

I Before bubbling, the event goes the otherway, from outermost to innermost element.This is called capturing.

I The capturing phase is ignored by allonEvent attributes and event listeners,except listeners with the useCaptureargument set to true:document.getElementById("myId").

addEventListener("click", handler, true);

17 / 93

Page 41: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Event Capturing

I Before bubbling, the event goes the otherway, from outermost to innermost element.This is called capturing.

I The capturing phase is ignored by allonEvent attributes and event listeners,except listeners with the useCaptureargument set to true:document.getElementById("myId").

addEventListener("click", handler, true);

17 / 93

Page 42: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Navigating the DOM Tree

Image fromhttp://www.w3schools.com/js/js_htmldom_navigation.asp

I The image to the leftillustrates parent, child andsibling relationships betweennodes in the DOM tree.

I The DOM tree can benavigated with the nodeproperties parentNode,childNodes,firstChild,lastChild,nextSibling, andpreviousSibling

18 / 93

Page 43: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Navigating the DOM Tree

Image fromhttp://www.w3schools.com/js/js_htmldom_navigation.asp

I The image to the leftillustrates parent, child andsibling relationships betweennodes in the DOM tree.

I The DOM tree can benavigated with the nodeproperties parentNode,childNodes,firstChild,lastChild,nextSibling, andpreviousSibling

18 / 93

Page 44: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Navigating the DOM Tree (Cont’d)I Note that, in the code below, the <p> node

contains a child text node with the valuethe text<p>the text</p>

I Text content can be accessed with theinnerHTML and nodeValue properties.<p id="demo">text content</p>

Using innerHTML:var text = document.getElementById("demo").

innerHTML;

Using nodeValue:var text = document.getElementById("demo").childNodes[0].nodeValue;

19 / 93

Page 45: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Navigating the DOM Tree (Cont’d)I Note that, in the code below, the <p> node

contains a child text node with the valuethe text<p>the text</p>

I Text content can be accessed with theinnerHTML and nodeValue properties.<p id="demo">text content</p>

Using innerHTML:var text = document.getElementById("demo").

innerHTML;

Using nodeValue:var text = document.getElementById("demo").childNodes[0].nodeValue;

19 / 93

Page 46: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Adding Elements

I To add a new element, first create it, theninsert it in the DOM tree.<div id="target"></div>

var elem = document.createElement("p");var text =

document.createTextNode("added element");elem.appendChild(text);document.getElementById("target").

appendChild(elem);

20 / 93

Page 47: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Removing Elements

I To remove an element, use theremoveChild method.<div id="parent"><p>To be removed</p>

</div>

var parent =document.getElementById("parent");

var child =parent.getElementsByTagName("p")[0];

parent.removeChild(child);

21 / 93

Page 48: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Question 2

22 / 93

Page 49: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Section

The Document Object Model, DOM

The Browser Object Model, BOM

The jQuery JavaScript Library

AJAX

Long Polling

WebSocket

The Knockout JavaScript Framework

23 / 93

Page 50: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Browser Object Model, BOM

I While the DOM provides an API foraccessing the current document, theBrowser Object Model, BOM, provides anAPI that gives access to the browser.

I The BOM is not standardized, but more orless the same methods are implemented inall modern browsers.

I The following slides contain a shortoverview of major objects and methods, togive an idea of what can be done with theBOM.

24 / 93

Page 51: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Browser Object Model, BOM

I While the DOM provides an API foraccessing the current document, theBrowser Object Model, BOM, provides anAPI that gives access to the browser.

I The BOM is not standardized, but more orless the same methods are implemented inall modern browsers.

I The following slides contain a shortoverview of major objects and methods, togive an idea of what can be done with theBOM.

24 / 93

Page 52: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Browser Object Model, BOM

I While the DOM provides an API foraccessing the current document, theBrowser Object Model, BOM, provides anAPI that gives access to the browser.

I The BOM is not standardized, but more orless the same methods are implemented inall modern browsers.

I The following slides contain a shortoverview of major objects and methods, togive an idea of what can be done with theBOM.

24 / 93

Page 53: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

BOM Objects

I The window object has:I Properties for height and width of the browser

window.I Methods to open, close, move and resize the

browser window.I Methods to execute some code at specified

time-intervals.I The location object has:

I Properties that gives information about thecurrent URL.

I The assign method that loads a newdocument.

25 / 93

Page 54: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

BOM Objects

I The window object has:I Properties for height and width of the browser

window.I Methods to open, close, move and resize the

browser window.I Methods to execute some code at specified

time-intervals.I The location object has:

I Properties that gives information about thecurrent URL.

I The assign method that loads a newdocument.

25 / 93

Page 55: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

BOM Objects (Cont’d)

I The navigator object can giveinformation about browser type andbrowser features.

I The screen object has properties forheight, width and pixel depth of the user’sscreen.

I The document object has the cookieproperty, which is used to get and setcookies.

26 / 93

Page 56: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

BOM Objects (Cont’d)

I The navigator object can giveinformation about browser type andbrowser features.

I The screen object has properties forheight, width and pixel depth of the user’sscreen.

I The document object has the cookieproperty, which is used to get and setcookies.

26 / 93

Page 57: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

BOM Objects (Cont’d)

I The navigator object can giveinformation about browser type andbrowser features.

I The screen object has properties forheight, width and pixel depth of the user’sscreen.

I The document object has the cookieproperty, which is used to get and setcookies.

26 / 93

Page 58: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Section

The Document Object Model, DOM

The Browser Object Model, BOM

The jQuery JavaScript Library

AJAX

Long Polling

WebSocket

The Knockout JavaScript Framework

27 / 93

Page 59: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The jQuery Library

I jQuery provides an API that simplifies manycommon JavaScript tasks, like DOMmanipulation, CSS manipulation, eventhandling, effects and animation.

I There are many jQuery plugins that providemore features.

I jQuery hides cross-browser issues, alljQuery code will work the same way in allbrowsers supporting jQuery.

I jQuery is very commonly used.

28 / 93

Page 60: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The jQuery Library

I jQuery provides an API that simplifies manycommon JavaScript tasks, like DOMmanipulation, CSS manipulation, eventhandling, effects and animation.

I There are many jQuery plugins that providemore features.

I jQuery hides cross-browser issues, alljQuery code will work the same way in allbrowsers supporting jQuery.

I jQuery is very commonly used.

28 / 93

Page 61: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The jQuery Library

I jQuery provides an API that simplifies manycommon JavaScript tasks, like DOMmanipulation, CSS manipulation, eventhandling, effects and animation.

I There are many jQuery plugins that providemore features.

I jQuery hides cross-browser issues, alljQuery code will work the same way in allbrowsers supporting jQuery.

I jQuery is very commonly used.

28 / 93

Page 62: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The jQuery Library

I jQuery provides an API that simplifies manycommon JavaScript tasks, like DOMmanipulation, CSS manipulation, eventhandling, effects and animation.

I There are many jQuery plugins that providemore features.

I jQuery hides cross-browser issues, alljQuery code will work the same way in allbrowsers supporting jQuery.

I jQuery is very commonly used.

28 / 93

Page 63: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Installing jQuery

I jQuery is a JavaScript file, to use it you justhave to provide a link to that file.

I The jQuery library file comes in twoversions:

I A development version, which isuncompressed and therefore readable.

I A live website version, which has beenminified and compressed and therefore is notreadable. Instead it is shorter and therebyfaster to download.

29 / 93

Page 64: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Installing jQuery

I jQuery is a JavaScript file, to use it you justhave to provide a link to that file.

I The jQuery library file comes in twoversions:

I A development version, which isuncompressed and therefore readable.

I A live website version, which has beenminified and compressed and therefore is notreadable. Instead it is shorter and therebyfaster to download.

29 / 93

Page 65: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Installing jQuery (Cont’d)

I Either you download it from jquery.comand place it on your server, or you providea link to a Content Delivery Network, CDN,as follows:<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

I Using a CDN is normally faster, since:

I The file is delivered from the CDNs serverclosest to the user.

I Many users already have downloaded jQueryfrom the CDN when visiting another site. As aresult, it is loaded from browser cache.

30 / 93

Page 66: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Installing jQuery (Cont’d)

I Either you download it from jquery.comand place it on your server, or you providea link to a Content Delivery Network, CDN,as follows:<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

I Using a CDN is normally faster, since:I The file is delivered from the CDNs server

closest to the user.

I Many users already have downloaded jQueryfrom the CDN when visiting another site. As aresult, it is loaded from browser cache.

30 / 93

Page 67: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Installing jQuery (Cont’d)

I Either you download it from jquery.comand place it on your server, or you providea link to a Content Delivery Network, CDN,as follows:<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

I Using a CDN is normally faster, since:I The file is delivered from the CDNs server

closest to the user.I Many users already have downloaded jQuery

from the CDN when visiting another site. As aresult, it is loaded from browser cache.

30 / 93

Page 68: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Installing jQuery (Cont’d)

I Either you download it from jquery.comand place it on your server, or you providea link to a Content Delivery Network, CDN,as follows:<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

I Using a CDN is normally faster, since:I The file is delivered from the CDNs server

closest to the user.I Many users already have downloaded jQuery

from the CDN when visiting another site. As aresult, it is loaded from browser cache.

30 / 93

Page 69: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The jQuery FunctionI Very central to jQuery is the jQuery function, which

has two names, jQuery and the commonly used $.

I Remember that $ is a perfectly legal JavaScriptidentifier, there is nothing magic about that name.

I The jQuery function normally takes one parameter,which is either a CSS selector or a reference to anobject in the document, and returns a jQuery objectwrapping all HTML element(s) corresponding to thesearch criteria.$(document) //The document object.$(this) //The current element.$(".c") //All elements with class "c"$(div) //All div elements.

I Any CSS selector can be used as search criteria.

31 / 93

Page 70: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The jQuery FunctionI Very central to jQuery is the jQuery function, which

has two names, jQuery and the commonly used $.

I Remember that $ is a perfectly legal JavaScriptidentifier, there is nothing magic about that name.

I The jQuery function normally takes one parameter,which is either a CSS selector or a reference to anobject in the document, and returns a jQuery objectwrapping all HTML element(s) corresponding to thesearch criteria.$(document) //The document object.$(this) //The current element.$(".c") //All elements with class "c"$(div) //All div elements.

I Any CSS selector can be used as search criteria.

31 / 93

Page 71: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The jQuery FunctionI Very central to jQuery is the jQuery function, which

has two names, jQuery and the commonly used $.

I Remember that $ is a perfectly legal JavaScriptidentifier, there is nothing magic about that name.

I The jQuery function normally takes one parameter,which is either a CSS selector or a reference to anobject in the document, and returns a jQuery objectwrapping all HTML element(s) corresponding to thesearch criteria.$(document) //The document object.$(this) //The current element.$(".c") //All elements with class "c"$(div) //All div elements.

I Any CSS selector can be used as search criteria.

31 / 93

Page 72: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The jQuery FunctionI Very central to jQuery is the jQuery function, which

has two names, jQuery and the commonly used $.

I Remember that $ is a perfectly legal JavaScriptidentifier, there is nothing magic about that name.

I The jQuery function normally takes one parameter,which is either a CSS selector or a reference to anobject in the document, and returns a jQuery objectwrapping all HTML element(s) corresponding to thesearch criteria.$(document) //The document object.$(this) //The current element.$(".c") //All elements with class "c"$(div) //All div elements.

I Any CSS selector can be used as search criteria.

31 / 93

Page 73: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The jQuery Object

I The jQuery object also has two names, jQueryand the commonly used $.

I The jQuery object contains many methods thatoperate on the wrapped HTML element. Forexample the html method that gets or sets theHTML content of the wrapped element:

/* Store the HTML of the element withid "someId" in the variable "content". */var content = $("#someId").html();

/* Set the HTML of the element withid "someId" to "content<br/>". */$("#someId").html(content + "<br/>");

32 / 93

Page 74: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The jQuery Object

I The jQuery object also has two names, jQueryand the commonly used $.

I The jQuery object contains many methods thatoperate on the wrapped HTML element. Forexample the html method that gets or sets theHTML content of the wrapped element:

/* Store the HTML of the element withid "someId" in the variable "content". */var content = $("#someId").html();

/* Set the HTML of the element withid "someId" to "content<br/>". */$("#someId").html(content + "<br/>");

32 / 93

Page 75: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The jQuery Object (Cont’d)

I The jQuery object supports arraysubscripting via brackets:$("h1")[0]; //The first h1 element.

I The jQuery object also has utility methodsthat are not related to a HTML element:// Returns the string "extra whitespace"$.trim( " extra whitespace " );

33 / 93

Page 76: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The jQuery Object (Cont’d)

I The jQuery object supports arraysubscripting via brackets:$("h1")[0]; //The first h1 element.

I The jQuery object also has utility methodsthat are not related to a HTML element:// Returns the string "extra whitespace"$.trim( " extra whitespace " );

33 / 93

Page 77: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Event Handlers

I In jQuery, an event handling function ispassed as argument to a method with theevent name in the jQuery object wrappingthe desired event source.

I The following code adds an event handlerto all <p> elements. The event handler willchange the paragraph’s text toYou clicked! when the user clicks it.$("p").click(function(){$(this).html("You clicked");

});

34 / 93

Page 78: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Event Handlers

I In jQuery, an event handling function ispassed as argument to a method with theevent name in the jQuery object wrappingthe desired event source.

I The following code adds an event handlerto all <p> elements. The event handler willchange the paragraph’s text toYou clicked! when the user clicks it.$("p").click(function(){$(this).html("You clicked");

});

34 / 93

Page 79: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Document Ready EventI jQuery defines the document ready event, which is

fired when the DOM has been constructed.

I It is usually best to wait for this event before runningJavaScript code, to avoid operating on elements thathave not been defined.

I It is normally not necessary to wait for the JavaScriptload event, which fires when everything, includingimages, is loaded and rendered.

I Therefore, JavaScript code is normally written likethis:

$(document).ready(function(){// JavaScript code here...

});

35 / 93

Page 80: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Document Ready EventI jQuery defines the document ready event, which is

fired when the DOM has been constructed.

I It is usually best to wait for this event before runningJavaScript code, to avoid operating on elements thathave not been defined.

I It is normally not necessary to wait for the JavaScriptload event, which fires when everything, includingimages, is loaded and rendered.

I Therefore, JavaScript code is normally written likethis:

$(document).ready(function(){// JavaScript code here...

});

35 / 93

Page 81: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Document Ready EventI jQuery defines the document ready event, which is

fired when the DOM has been constructed.

I It is usually best to wait for this event before runningJavaScript code, to avoid operating on elements thathave not been defined.

I It is normally not necessary to wait for the JavaScriptload event, which fires when everything, includingimages, is loaded and rendered.

I Therefore, JavaScript code is normally written likethis:

$(document).ready(function(){// JavaScript code here...

});

35 / 93

Page 82: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Document Ready EventI jQuery defines the document ready event, which is

fired when the DOM has been constructed.

I It is usually best to wait for this event before runningJavaScript code, to avoid operating on elements thathave not been defined.

I It is normally not necessary to wait for the JavaScriptload event, which fires when everything, includingimages, is loaded and rendered.

I Therefore, JavaScript code is normally written likethis:

$(document).ready(function(){// JavaScript code here...

});

35 / 93

Page 83: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

CSS Rules

I When passed a CSS property name, thecss method returns the value of thatproperty.$("body").css("background-color"));

I When passed one or more property:valuepairs, those rules are set for the specifiedelement(s).$("body").css("background-color","yellow");

36 / 93

Page 84: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

CSS Rules

I When passed a CSS property name, thecss method returns the value of thatproperty.$("body").css("background-color"));

I When passed one or more property:valuepairs, those rules are set for the specifiedelement(s).$("body").css("background-color","yellow");

36 / 93

Page 85: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Effects

I There are lots of effects provided by jQuery,here are some examples.

I The hide and show methods can hide/showelements. It is also possible to specify thespeed of the (dis)appearance.

I Various fade methods causes an element tofade in/out.

I Various slide methods causes an elementto slide up/down.

I The animate method is used to createcustom animations.

37 / 93

Page 86: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Effects

I There are lots of effects provided by jQuery,here are some examples.

I The hide and show methods can hide/showelements. It is also possible to specify thespeed of the (dis)appearance.

I Various fade methods causes an element tofade in/out.

I Various slide methods causes an elementto slide up/down.

I The animate method is used to createcustom animations.

37 / 93

Page 87: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Effects

I There are lots of effects provided by jQuery,here are some examples.

I The hide and show methods can hide/showelements. It is also possible to specify thespeed of the (dis)appearance.

I Various fade methods causes an element tofade in/out.

I Various slide methods causes an elementto slide up/down.

I The animate method is used to createcustom animations.

37 / 93

Page 88: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Effects

I There are lots of effects provided by jQuery,here are some examples.

I The hide and show methods can hide/showelements. It is also possible to specify thespeed of the (dis)appearance.

I Various fade methods causes an element tofade in/out.

I Various slide methods causes an elementto slide up/down.

I The animate method is used to createcustom animations.

37 / 93

Page 89: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Effects

I There are lots of effects provided by jQuery,here are some examples.

I The hide and show methods can hide/showelements. It is also possible to specify thespeed of the (dis)appearance.

I Various fade methods causes an element tofade in/out.

I Various slide methods causes an elementto slide up/down.

I The animate method is used to createcustom animations.

37 / 93

Page 90: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Effects (Cont’d)

I Effects can have callback functions that areexecuted when the effect is done.$("button").click(function(){$("p").hide("slow",function(){

alert("The paragraph is now hidden");});

});

38 / 93

Page 91: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

jQuery Method Chaining

I Many of the element manipulation methodsof the jQuery object return the jQueryobject itself.

I This means it is possible to create chains ofsuch methods.$("button").click(function(){$("#p1").css("color","blue")

.slideUp(3000)

.slideDown(2000);});

39 / 93

Page 92: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

jQuery Method Chaining

I Many of the element manipulation methodsof the jQuery object return the jQueryobject itself.

I This means it is possible to create chains ofsuch methods.$("button").click(function(){$("#p1").css("color","blue")

.slideUp(3000)

.slideDown(2000);});

39 / 93

Page 93: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Element Content and ElementAttributes

I The text method is used to access text content ofan HTML element, the html method is used for textcontent with HTML tags, the val method is used forform field values, and attr is used for an element’sattributes.

I If called without arguments, these methods returnthe current value. If called with arguments they set anew value.$("#btn").click(function(){var current = $("#test").html());

});

$("#btn").click(function(){$("#textField").val("New value");

});40 / 93

Page 94: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Element Content and ElementAttributes

I The text method is used to access text content ofan HTML element, the html method is used for textcontent with HTML tags, the val method is used forform field values, and attr is used for an element’sattributes.

I If called without arguments, these methods returnthe current value. If called with arguments they set anew value.$("#btn").click(function(){var current = $("#test").html());

});

$("#btn").click(function(){$("#textField").val("New value");

});40 / 93

Page 95: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Element Content and ElementAttributes (Cont’d)

I The text, html, val, and attrmethods can have callback functions.

I The callback function takes two parameters,the index of the current element in the list ofelements selected and the original value.

I The return value of the callback functionbecomes the new text of the element.$("#btn").click(function(){

$("p").text(function(i,oldText){return "Old text: " + oldText +

", index: " + i;});

});

41 / 93

Page 96: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Element Content and ElementAttributes (Cont’d)

I The text, html, val, and attrmethods can have callback functions.

I The callback function takes two parameters,the index of the current element in the list ofelements selected and the original value.

I The return value of the callback functionbecomes the new text of the element.$("#btn").click(function(){$("p").text(function(i,oldText){

return "Old text: " + oldText +", index: " + i;

});});

41 / 93

Page 97: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Element Content and ElementAttributes (Cont’d)

I The text, html, val, and attrmethods can have callback functions.

I The callback function takes two parameters,the index of the current element in the list ofelements selected and the original value.

I The return value of the callback functionbecomes the new text of the element.$("#btn").click(function(){$("p").text(function(i,oldText){

return "Old text: " + oldText +", index: " + i;

});});

41 / 93

Page 98: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

To Add or Remove Elements

I The append, prepend, before, andafter methods are used to add elements.// Append a list item to the ordered list// with id "someList".$("#someList").

append("<li>Appended item</li>");

I The remove and empty methods areused to remove elements.// Remove the element with id "#menu".$("#menu").remove();

42 / 93

Page 99: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

To Add or Remove Elements

I The append, prepend, before, andafter methods are used to add elements.// Append a list item to the ordered list// with id "someList".$("#someList").

append("<li>Appended item</li>");

I The remove and empty methods areused to remove elements.// Remove the element with id "#menu".$("#menu").remove();

42 / 93

Page 100: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

DimensionsThe following image, taken fromhttp://www.w3schools.com/jquery/jquery_dimensions.asp, illustrates themethods used to set or get element dimensions.

43 / 93

Page 101: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Traversing the DOM TreeHere are samples of jQuery methods used totraverse the DOM tree.

parent Returns the parent on the nearest higherlevel.

parents Returns all parents all the way up to the htmlelement.

children Returns all children on the nearest lowerlevel.

find Returns all descendants on all lower levels.

siblings Returns all siblings.

filtering The first, last, eq, and filtermethods can be used to filter the searchresults of the methods above.

44 / 93

Page 102: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Traversing the DOM TreeHere are samples of jQuery methods used totraverse the DOM tree.

parent Returns the parent on the nearest higherlevel.

parents Returns all parents all the way up to the htmlelement.

children Returns all children on the nearest lowerlevel.

find Returns all descendants on all lower levels.

siblings Returns all siblings.

filtering The first, last, eq, and filtermethods can be used to filter the searchresults of the methods above.

44 / 93

Page 103: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Traversing the DOM TreeHere are samples of jQuery methods used totraverse the DOM tree.

parent Returns the parent on the nearest higherlevel.

parents Returns all parents all the way up to the htmlelement.

children Returns all children on the nearest lowerlevel.

find Returns all descendants on all lower levels.

siblings Returns all siblings.

filtering The first, last, eq, and filtermethods can be used to filter the searchresults of the methods above.

44 / 93

Page 104: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Traversing the DOM TreeHere are samples of jQuery methods used totraverse the DOM tree.

parent Returns the parent on the nearest higherlevel.

parents Returns all parents all the way up to the htmlelement.

children Returns all children on the nearest lowerlevel.

find Returns all descendants on all lower levels.

siblings Returns all siblings.

filtering The first, last, eq, and filtermethods can be used to filter the searchresults of the methods above.

44 / 93

Page 105: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Traversing the DOM TreeHere are samples of jQuery methods used totraverse the DOM tree.

parent Returns the parent on the nearest higherlevel.

parents Returns all parents all the way up to the htmlelement.

children Returns all children on the nearest lowerlevel.

find Returns all descendants on all lower levels.

siblings Returns all siblings.

filtering The first, last, eq, and filtermethods can be used to filter the searchresults of the methods above.

44 / 93

Page 106: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Traversing the DOM TreeHere are samples of jQuery methods used totraverse the DOM tree.

parent Returns the parent on the nearest higherlevel.

parents Returns all parents all the way up to the htmlelement.

children Returns all children on the nearest lowerlevel.

find Returns all descendants on all lower levels.

siblings Returns all siblings.

filtering The first, last, eq, and filtermethods can be used to filter the searchresults of the methods above.

44 / 93

Page 107: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Traversing the DOM TreeHere are samples of jQuery methods used totraverse the DOM tree.

parent Returns the parent on the nearest higherlevel.

parents Returns all parents all the way up to the htmlelement.

children Returns all children on the nearest lowerlevel.

find Returns all descendants on all lower levels.

siblings Returns all siblings.

filtering The first, last, eq, and filtermethods can be used to filter the searchresults of the methods above.

44 / 93

Page 108: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Question 3

45 / 93

Page 109: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Section

The Document Object Model, DOM

The Browser Object Model, BOM

The jQuery JavaScript Library

AJAX

Long Polling

WebSocket

The Knockout JavaScript Framework

46 / 93

Page 110: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Loading an Entire Page

I Traditionally, an entire page is loaded whenthe user clicks a link or a button.

I Here, to load an entire page means that allHTML in the page is read from the server.

I Dynamic data is included on the server,before the HTML is sent to the client, forexample using a PHP program.

I This behavior is appropriate if the entirepage content really must change, but that isoften not the case.

47 / 93

Page 111: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Loading an Entire Page

I Traditionally, an entire page is loaded whenthe user clicks a link or a button.

I Here, to load an entire page means that allHTML in the page is read from the server.

I Dynamic data is included on the server,before the HTML is sent to the client, forexample using a PHP program.

I This behavior is appropriate if the entirepage content really must change, but that isoften not the case.

47 / 93

Page 112: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Loading an Entire Page

I Traditionally, an entire page is loaded whenthe user clicks a link or a button.

I Here, to load an entire page means that allHTML in the page is read from the server.

I Dynamic data is included on the server,before the HTML is sent to the client, forexample using a PHP program.

I This behavior is appropriate if the entirepage content really must change, but that isoften not the case.

47 / 93

Page 113: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Loading an Entire Page

I Traditionally, an entire page is loaded whenthe user clicks a link or a button.

I Here, to load an entire page means that allHTML in the page is read from the server.

I Dynamic data is included on the server,before the HTML is sent to the client, forexample using a PHP program.

I This behavior is appropriate if the entirepage content really must change, but that isoften not the case.

47 / 93

Page 114: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Loading an Entire Page

Consider for example the sample chat application. All that

happens when the user clicks Send is that the new entry

is added, the rest of the page is untouched. 48 / 93

Page 115: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Repetition: The MVVM PatternI The philosophy behind

Model-View-ViewModel,MVVM, is to send onlystate changes fromserver to client.

I State changes, whichmeans new data, arestored in the viewmodel.

I Therefore, the viewmodel will alwayscontain the current state of the application.

I The browser view must reflect theviewmodel state, preferably using theobserver pattern.

49 / 93

Page 116: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Repetition: The MVVM PatternI The philosophy behind

Model-View-ViewModel,MVVM, is to send onlystate changes fromserver to client.

I State changes, whichmeans new data, arestored in the viewmodel.

I Therefore, the viewmodel will alwayscontain the current state of the application.

I The browser view must reflect theviewmodel state, preferably using theobserver pattern.

49 / 93

Page 117: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Repetition: The MVVM PatternI The philosophy behind

Model-View-ViewModel,MVVM, is to send onlystate changes fromserver to client.

I State changes, whichmeans new data, arestored in the viewmodel.

I Therefore, the viewmodel will alwayscontain the current state of the application.

I The browser view must reflect theviewmodel state, preferably using theobserver pattern.

49 / 93

Page 118: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Repetition: The MVVM PatternI The philosophy behind

Model-View-ViewModel,MVVM, is to send onlystate changes fromserver to client.

I State changes, whichmeans new data, arestored in the viewmodel.

I Therefore, the viewmodel will alwayscontain the current state of the application.

I The browser view must reflect theviewmodel state, preferably using theobserver pattern.

49 / 93

Page 119: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

AJAX: To Load Only Data

I The dominating method to request datafrom the server, without reloading the webpage, is Asynchronous JavaScript AndXML, AJAX.

I AJAX is basically a way to use existingtechnologies, such as JavaScript, HTTPand XML.

I No new language or markup.

I The only thing specific for AJAX is aJavaScript object, calledXMLHttpRequest, which isstandardized by W3C.

50 / 93

Page 120: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

AJAX: To Load Only Data

I The dominating method to request datafrom the server, without reloading the webpage, is Asynchronous JavaScript AndXML, AJAX.

I AJAX is basically a way to use existingtechnologies, such as JavaScript, HTTPand XML.

I No new language or markup.

I The only thing specific for AJAX is aJavaScript object, calledXMLHttpRequest, which isstandardized by W3C.

50 / 93

Page 121: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

AJAX: To Load Only Data

I The dominating method to request datafrom the server, without reloading the webpage, is Asynchronous JavaScript AndXML, AJAX.

I AJAX is basically a way to use existingtechnologies, such as JavaScript, HTTPand XML.

I No new language or markup.

I The only thing specific for AJAX is aJavaScript object, calledXMLHttpRequest, which isstandardized by W3C.

50 / 93

Page 122: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

How Does It Work?

I Web page is loaded only on first request.

I Subsequent requests come from JavaScriptcode, using XMLHttpRequest.

I The server returns only data, no markup.I Returned data is available to JavaScript

code, and is used to update the web page,by updating the DOM.

51 / 93

Page 123: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

How Does It Work?

I Web page is loaded only on first request.I Subsequent requests come from JavaScript

code, using XMLHttpRequest.

I The server returns only data, no markup.I Returned data is available to JavaScript

code, and is used to update the web page,by updating the DOM.

51 / 93

Page 124: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

How Does It Work?

I Web page is loaded only on first request.I Subsequent requests come from JavaScript

code, using XMLHttpRequest.I The server returns only data, no markup.

I Returned data is available to JavaScriptcode, and is used to update the web page,by updating the DOM.

51 / 93

Page 125: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

How Does It Work?

I Web page is loaded only on first request.I Subsequent requests come from JavaScript

code, using XMLHttpRequest.I The server returns only data, no markup.I Returned data is available to JavaScript

code, and is used to update the web page,by updating the DOM.

51 / 93

Page 126: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

How Does It Work?

I Web page is loaded only on first request.I Subsequent requests come from JavaScript

code, using XMLHttpRequest.I The server returns only data, no markup.I Returned data is available to JavaScript

code, and is used to update the web page,by updating the DOM.

51 / 93

Page 127: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

How Does It Work? (Cont’d)

I Note that AJAX requests are ordinaryHTTP GET or HTTP POST requests.

I The server directs the request to theresource specified in the URL, just as whenloading a HTML document.

I An AJAX request is normally handled by aprogram, for example PHP, which generatesa response containing the new data.

52 / 93

Page 128: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

How Does It Work? (Cont’d)

I Note that AJAX requests are ordinaryHTTP GET or HTTP POST requests.

I The server directs the request to theresource specified in the URL, just as whenloading a HTML document.

I An AJAX request is normally handled by aprogram, for example PHP, which generatesa response containing the new data.

52 / 93

Page 129: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

How Does It Work? (Cont’d)

I Note that AJAX requests are ordinaryHTTP GET or HTTP POST requests.

I The server directs the request to theresource specified in the URL, just as whenloading a HTML document.

I An AJAX request is normally handled by aprogram, for example PHP, which generatesa response containing the new data.

52 / 93

Page 130: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Data FormatI Client and server need to agree on the

format of the data included in the HTTPresponse.

I XML is an obvious option, but it has somedrawbacks:

I Interpreting an XML document requires extracode.

I Using a XSLT stylesheet to generate a view isa bit tricky.

I XML documents are quite long and wordy.I Therefore, JavaScript Object Notation,

JSON, is normally used instead of XML.I Compact and easy to translate to JavaScript

objects.

53 / 93

Page 131: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Data FormatI Client and server need to agree on the

format of the data included in the HTTPresponse.

I XML is an obvious option, but it has somedrawbacks:

I Interpreting an XML document requires extracode.

I Using a XSLT stylesheet to generate a view isa bit tricky.

I XML documents are quite long and wordy.I Therefore, JavaScript Object Notation,

JSON, is normally used instead of XML.I Compact and easy to translate to JavaScript

objects.

53 / 93

Page 132: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Data FormatI Client and server need to agree on the

format of the data included in the HTTPresponse.

I XML is an obvious option, but it has somedrawbacks:

I Interpreting an XML document requires extracode.

I Using a XSLT stylesheet to generate a view isa bit tricky.

I XML documents are quite long and wordy.I Therefore, JavaScript Object Notation,

JSON, is normally used instead of XML.I Compact and easy to translate to JavaScript

objects.

53 / 93

Page 133: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Data FormatI Client and server need to agree on the

format of the data included in the HTTPresponse.

I XML is an obvious option, but it has somedrawbacks:

I Interpreting an XML document requires extracode.

I Using a XSLT stylesheet to generate a view isa bit tricky.

I XML documents are quite long and wordy.

I Therefore, JavaScript Object Notation,JSON, is normally used instead of XML.

I Compact and easy to translate to JavaScriptobjects.

53 / 93

Page 134: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Data FormatI Client and server need to agree on the

format of the data included in the HTTPresponse.

I XML is an obvious option, but it has somedrawbacks:

I Interpreting an XML document requires extracode.

I Using a XSLT stylesheet to generate a view isa bit tricky.

I XML documents are quite long and wordy.I Therefore, JavaScript Object Notation,

JSON, is normally used instead of XML.I Compact and easy to translate to JavaScript

objects.

53 / 93

Page 135: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Data FormatI Client and server need to agree on the

format of the data included in the HTTPresponse.

I XML is an obvious option, but it has somedrawbacks:

I Interpreting an XML document requires extracode.

I Using a XSLT stylesheet to generate a view isa bit tricky.

I XML documents are quite long and wordy.I Therefore, JavaScript Object Notation,

JSON, is normally used instead of XML.I Compact and easy to translate to JavaScript

objects.

53 / 93

Page 136: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

JSONI The JSON syntax is very simple:

I Data is name/value pairs:"firstName":"Olle"

I Data is separated by commas.I Objects are denoted with { and }:

{"firstName":"Olle", "lastName":"Olsson"}

I Arrays are denoted with [ and ]:"employees":[{"firstName":"Olle", "lastName":"Olsson"},{"firstName":"Stina", "lastName":"Nilsson"}

]

I Data types are JavaScript types, for examplestring, “abcd”; integer, 123; boolean,false

54 / 93

Page 137: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

JSONI The JSON syntax is very simple:

I Data is name/value pairs:"firstName":"Olle"

I Data is separated by commas.

I Objects are denoted with { and }:{"firstName":"Olle", "lastName":"Olsson"}

I Arrays are denoted with [ and ]:"employees":[{"firstName":"Olle", "lastName":"Olsson"},{"firstName":"Stina", "lastName":"Nilsson"}

]

I Data types are JavaScript types, for examplestring, “abcd”; integer, 123; boolean,false

54 / 93

Page 138: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

JSONI The JSON syntax is very simple:

I Data is name/value pairs:"firstName":"Olle"

I Data is separated by commas.I Objects are denoted with { and }:

{"firstName":"Olle", "lastName":"Olsson"}

I Arrays are denoted with [ and ]:"employees":[{"firstName":"Olle", "lastName":"Olsson"},{"firstName":"Stina", "lastName":"Nilsson"}

]

I Data types are JavaScript types, for examplestring, “abcd”; integer, 123; boolean,false

54 / 93

Page 139: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

JSONI The JSON syntax is very simple:

I Data is name/value pairs:"firstName":"Olle"

I Data is separated by commas.I Objects are denoted with { and }:

{"firstName":"Olle", "lastName":"Olsson"}

I Arrays are denoted with [ and ]:"employees":[

{"firstName":"Olle", "lastName":"Olsson"},{"firstName":"Stina", "lastName":"Nilsson"}

]

I Data types are JavaScript types, for examplestring, “abcd”; integer, 123; boolean,false

54 / 93

Page 140: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

JSONI The JSON syntax is very simple:

I Data is name/value pairs:"firstName":"Olle"

I Data is separated by commas.I Objects are denoted with { and }:

{"firstName":"Olle", "lastName":"Olsson"}

I Arrays are denoted with [ and ]:"employees":[

{"firstName":"Olle", "lastName":"Olsson"},{"firstName":"Stina", "lastName":"Nilsson"}

]

I Data types are JavaScript types, for examplestring, “abcd”; integer, 123; boolean,false

54 / 93

Page 141: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

JSONI The JSON syntax is very simple:

I Data is name/value pairs:"firstName":"Olle"

I Data is separated by commas.I Objects are denoted with { and }:

{"firstName":"Olle", "lastName":"Olsson"}

I Arrays are denoted with [ and ]:"employees":[

{"firstName":"Olle", "lastName":"Olsson"},{"firstName":"Stina", "lastName":"Nilsson"}

]

I Data types are JavaScript types, for examplestring, “abcd”; integer, 123; boolean,false

54 / 93

Page 142: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

JSON is not an Alternative to XML

I Note that JSON is not a general alternativeto XML. There is nothing like namespace,DTD, Schema, XSLT or anything else of allthe XML standards.

I JSON is just a format suitable fortransferring JavaScript values.

55 / 93

Page 143: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

JSON is not an Alternative to XML

I Note that JSON is not a general alternativeto XML. There is nothing like namespace,DTD, Schema, XSLT or anything else of allthe XML standards.

I JSON is just a format suitable fortransferring JavaScript values.

55 / 93

Page 144: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Client: jQuery AJAX MethodsI Instead of covering the XMLHttpRequest object,

we will look at some convenient jQuery functions.

I getJSON sends a HTTP GET request. Data canbe included as a query string and the response isparsed as JSON data.

I $.getJSON(url, "reqData=" + someVariable,function(returnedData) {//Handle returnedData, which is//the received JSON data, parsed//to a JavaScript variable.

});

An HTTP GET request is sent to the URL specifiedin url. The request has the query stringreqData=<value of someVariable> andthe anonymous callback function is executed whenthe server’s response arrives.

56 / 93

Page 145: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Client: jQuery AJAX MethodsI Instead of covering the XMLHttpRequest object,

we will look at some convenient jQuery functions.

I getJSON sends a HTTP GET request. Data canbe included as a query string and the response isparsed as JSON data.

I $.getJSON(url, "reqData=" + someVariable,function(returnedData) {

//Handle returnedData, which is//the received JSON data, parsed//to a JavaScript variable.

});

An HTTP GET request is sent to the URL specifiedin url. The request has the query stringreqData=<value of someVariable> andthe anonymous callback function is executed whenthe server’s response arrives. 56 / 93

Page 146: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Client: jQuery AJAX MethodsI Instead of covering the XMLHttpRequest object,

we will look at some convenient jQuery functions.

I getJSON sends a HTTP GET request. Data canbe included as a query string and the response isparsed as JSON data.

I $.getJSON(url, "reqData=" + someVariable,function(returnedData) {

//Handle returnedData, which is//the received JSON data, parsed//to a JavaScript variable.

});

An HTTP GET request is sent to the URL specifiedin url. The request has the query stringreqData=<value of someVariable> andthe anonymous callback function is executed whenthe server’s response arrives. 56 / 93

Page 147: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

jQuery AJAX Methods (Cont’d)

I post sends data with a HTTP POSTrequest.

I $.post(url, "data=" + someVariable);

An HTTP POST request is sent to the URLspecified in url. The request has the bodydata=<value of someVariable>.

I jQuery has many more AJAX methods.

57 / 93

Page 148: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

jQuery AJAX Methods (Cont’d)

I post sends data with a HTTP POSTrequest.

I $.post(url, "data=" + someVariable);

An HTTP POST request is sent to the URLspecified in url. The request has the bodydata=<value of someVariable>.

I jQuery has many more AJAX methods.

57 / 93

Page 149: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

jQuery AJAX Methods (Cont’d)

I post sends data with a HTTP POSTrequest.

I $.post(url, "data=" + someVariable);

An HTTP POST request is sent to the URLspecified in url. The request has the bodydata=<value of someVariable>.

I jQuery has many more AJAX methods.

57 / 93

Page 150: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Server: JSON handling inPHP

I Remember that an AJAX request is anormal HTTP request.

I Therefore, to handle an AJAX request is nodifferent from other request handling.

I What is specific for AJAX interaction, is thatwe have to generate a JSON response.

I json_encode($aPhpObject)

The json_encode PHP method encodesthe PHP object in aPhpObject to JSONrepresentation.

58 / 93

Page 151: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Server: JSON handling inPHP

I Remember that an AJAX request is anormal HTTP request.

I Therefore, to handle an AJAX request is nodifferent from other request handling.

I What is specific for AJAX interaction, is thatwe have to generate a JSON response.

I json_encode($aPhpObject)

The json_encode PHP method encodesthe PHP object in aPhpObject to JSONrepresentation.

58 / 93

Page 152: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Server: JSON handling inPHP

I Remember that an AJAX request is anormal HTTP request.

I Therefore, to handle an AJAX request is nodifferent from other request handling.

I What is specific for AJAX interaction, is thatwe have to generate a JSON response.

I json_encode($aPhpObject)

The json_encode PHP method encodesthe PHP object in aPhpObject to JSONrepresentation.

58 / 93

Page 153: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Server: JSON handling inPHP

I Remember that an AJAX request is anormal HTTP request.

I Therefore, to handle an AJAX request is nodifferent from other request handling.

I What is specific for AJAX interaction, is thatwe have to generate a JSON response.

I json_encode($aPhpObject)

The json_encode PHP method encodesthe PHP object in aPhpObject to JSONrepresentation.

58 / 93

Page 154: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

JSON handling in PHP (Cont’d)class SomeClass implements \JsonSerializable {

private $some_var;...public function jsonSerialize() {

$json_obj = new \stdClass;$json_obj->someVar = $this->some_var;...return $json_obj;

}

I The object that shall be JSON encoded must be of aclass that implements JsonSerializable.

I That class must have a method calledjsonSerialize, which returns an objectcontaining all relevant fields.

I That returned object must be possible to encodewith json_encode.

59 / 93

Page 155: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

JSON handling in PHP (Cont’d)class SomeClass implements \JsonSerializable {

private $some_var;...public function jsonSerialize() {

$json_obj = new \stdClass;$json_obj->someVar = $this->some_var;...return $json_obj;

}

I The object that shall be JSON encoded must be of aclass that implements JsonSerializable.

I That class must have a method calledjsonSerialize, which returns an objectcontaining all relevant fields.

I That returned object must be possible to encodewith json_encode.

59 / 93

Page 156: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

JSON handling in PHP (Cont’d)class SomeClass implements \JsonSerializable {

private $some_var;...public function jsonSerialize() {

$json_obj = new \stdClass;$json_obj->someVar = $this->some_var;...return $json_obj;

}

I The object that shall be JSON encoded must be of aclass that implements JsonSerializable.

I That class must have a method calledjsonSerialize, which returns an objectcontaining all relevant fields.

I That returned object must be possible to encodewith json_encode.

59 / 93

Page 157: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Question 4

60 / 93

Page 158: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Section

The Document Object Model, DOM

The Browser Object Model, BOM

The jQuery JavaScript Library

AJAX

Long Polling

WebSocket

The Knockout JavaScript Framework

61 / 93

Page 159: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Long PollingI Long Polling, also called Comet, is a

programming technique that enables webservers to push data to a client even if theclient has not explicitly requested that data.

1. The browser makes an Ajax request to the server,no matter whether there is data to fetch or not.

2. The request is left unanswered by the server, untilthere is data to send to the browser.

3. When receiving the server response, the browserimmediately makes a new request in order to obtainthe next data set.

4. Start over from point one again.

62 / 93

Page 160: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Long PollingI Long Polling, also called Comet, is a

programming technique that enables webservers to push data to a client even if theclient has not explicitly requested that data.

1. The browser makes an Ajax request to the server,no matter whether there is data to fetch or not.

2. The request is left unanswered by the server, untilthere is data to send to the browser.

3. When receiving the server response, the browserimmediately makes a new request in order to obtainthe next data set.

4. Start over from point one again.

62 / 93

Page 161: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Long PollingI Long Polling, also called Comet, is a

programming technique that enables webservers to push data to a client even if theclient has not explicitly requested that data.

1. The browser makes an Ajax request to the server,no matter whether there is data to fetch or not.

2. The request is left unanswered by the server, untilthere is data to send to the browser.

3. When receiving the server response, the browserimmediately makes a new request in order to obtainthe next data set.

4. Start over from point one again.

62 / 93

Page 162: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Long PollingI Long Polling, also called Comet, is a

programming technique that enables webservers to push data to a client even if theclient has not explicitly requested that data.

1. The browser makes an Ajax request to the server,no matter whether there is data to fetch or not.

2. The request is left unanswered by the server, untilthere is data to send to the browser.

3. When receiving the server response, the browserimmediately makes a new request in order to obtainthe next data set.

4. Start over from point one again.

62 / 93

Page 163: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Long PollingI Long Polling, also called Comet, is a

programming technique that enables webservers to push data to a client even if theclient has not explicitly requested that data.

1. The browser makes an Ajax request to the server,no matter whether there is data to fetch or not.

2. The request is left unanswered by the server, untilthere is data to send to the browser.

3. When receiving the server response, the browserimmediately makes a new request in order to obtainthe next data set.

4. Start over from point one again.

62 / 93

Page 164: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Long Polling JavaScript Client$(document).ready(function () {

function fetchFromServer() {$.getJSON("get-msg.php",

function (response) {$("#fromServer").prepend("<p>" + response +

"</p>");fetchFromServer();

});}

fetchFromServer();});

Long polling is achieved by the call tofetchFromServer in red. This way a newcall is made as soon a response has beenhandled.

63 / 93

Page 165: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Long Polling PHP Server

1 define("ONE_SEC", 1);2 define("FILE_PATH", "msg-to-client.txt");34 while (TRUE) {5 $msg = \file_get_contents(FILE_PATH);6 if ($msg !== ’’) {7 \file_put_contents(FILE_PATH, ’’);8 echo \json_encode($msg);9 return;

10 }11 \sleep(ONE_SEC);12 }

I Line eleven pauses execution one second.

64 / 93

Page 166: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

A Word of WarningI The server will not handle multiple

simultaneous requests in the same session.If one request is being handled, otherrequests in the same session are blocked.

I Therefore, if the server has started asession, it is best to stop the session beforecalling sleep.

I \session_write_close();\sleep(self::ONE_SEC);\session_start();

session_write_close saves sessiondata and closes the session. This is whathappens every time a response has beensent, if a session was started.

65 / 93

Page 167: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

A Word of WarningI The server will not handle multiple

simultaneous requests in the same session.If one request is being handled, otherrequests in the same session are blocked.

I Therefore, if the server has started asession, it is best to stop the session beforecalling sleep.

I \session_write_close();\sleep(self::ONE_SEC);\session_start();

session_write_close saves sessiondata and closes the session. This is whathappens every time a response has beensent, if a session was started.

65 / 93

Page 168: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

A Word of WarningI The server will not handle multiple

simultaneous requests in the same session.If one request is being handled, otherrequests in the same session are blocked.

I Therefore, if the server has started asession, it is best to stop the session beforecalling sleep.

I \session_write_close();\sleep(self::ONE_SEC);\session_start();

session_write_close saves sessiondata and closes the session. This is whathappens every time a response has beensent, if a session was started.

65 / 93

Page 169: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

One More Word of Warning

I The php engine does not allow a script toexecute more than a specified time, whichby default is 30s. To make a long pollingrequest wait indefinitely, turn this off bycalling \set_time_limit(0);

66 / 93

Page 170: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Section

The Document Object Model, DOM

The Browser Object Model, BOM

The jQuery JavaScript Library

AJAX

Long Polling

WebSocket

The Knockout JavaScript Framework

67 / 93

Page 171: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

WebSocketI WebSocket is a W3C specification.

I Specifies a full-duplex, persistent, TCP connectionbetween browser and server.

I Endpoints are identified by URIs.

I ws://host:port/path (plain websocketconnection)

I wss://host:port/path (encrypted websocketconnection)

I Web sockets are message based, endpointsexchange messages (text or binary).

I A generic transport service, like TCP. Just like manyconnection-oriented protocols are built on top ofTCP (HTTP, FTP, POP3, IMAP, etc), there are manymessage-oriented protocols on top of web sockets.

68 / 93

Page 172: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

WebSocketI WebSocket is a W3C specification.

I Specifies a full-duplex, persistent, TCP connectionbetween browser and server.

I Endpoints are identified by URIs.I ws://host:port/path (plain websocket

connection)I wss://host:port/path (encrypted websocket

connection)

I Web sockets are message based, endpointsexchange messages (text or binary).

I A generic transport service, like TCP. Just like manyconnection-oriented protocols are built on top ofTCP (HTTP, FTP, POP3, IMAP, etc), there are manymessage-oriented protocols on top of web sockets.

68 / 93

Page 173: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

WebSocketI WebSocket is a W3C specification.

I Specifies a full-duplex, persistent, TCP connectionbetween browser and server.

I Endpoints are identified by URIs.I ws://host:port/path (plain websocket

connection)I wss://host:port/path (encrypted websocket

connection)

I Web sockets are message based, endpointsexchange messages (text or binary).

I A generic transport service, like TCP. Just like manyconnection-oriented protocols are built on top ofTCP (HTTP, FTP, POP3, IMAP, etc), there are manymessage-oriented protocols on top of web sockets.

68 / 93

Page 174: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

WebSocketI WebSocket is a W3C specification.

I Specifies a full-duplex, persistent, TCP connectionbetween browser and server.

I Endpoints are identified by URIs.I ws://host:port/path (plain websocket

connection)I wss://host:port/path (encrypted websocket

connection)

I Web sockets are message based, endpointsexchange messages (text or binary).

I A generic transport service, like TCP. Just like manyconnection-oriented protocols are built on top ofTCP (HTTP, FTP, POP3, IMAP, etc), there are manymessage-oriented protocols on top of web sockets.

68 / 93

Page 175: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

WebSocketI WebSocket is a W3C specification.

I Specifies a full-duplex, persistent, TCP connectionbetween browser and server.

I Endpoints are identified by URIs.I ws://host:port/path (plain websocket

connection)I wss://host:port/path (encrypted websocket

connection)

I Web sockets are message based, endpointsexchange messages (text or binary).

I A generic transport service, like TCP. Just like manyconnection-oriented protocols are built on top ofTCP (HTTP, FTP, POP3, IMAP, etc), there are manymessage-oriented protocols on top of web sockets.

68 / 93

Page 176: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

A New Kind of Web?I The W3C specification defines a JavaScript

endpoint, and is implemented by all majorbrowsers.

I There are endpoints for all majorserver-side technologies, e.g., PHP, Java,.NET, Python, Ruby.

I In conclusion, any browser or server canhave a full-duplex connection with any otherbrowser or server.

I The browser is no longer a just a userinterface. It becomes a node in a network,that can be programmed (in JavaScript) todo anything, and that can communicate(over websockets) with any other node.

69 / 93

Page 177: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

A New Kind of Web?I The W3C specification defines a JavaScript

endpoint, and is implemented by all majorbrowsers.

I There are endpoints for all majorserver-side technologies, e.g., PHP, Java,.NET, Python, Ruby.

I In conclusion, any browser or server canhave a full-duplex connection with any otherbrowser or server.

I The browser is no longer a just a userinterface. It becomes a node in a network,that can be programmed (in JavaScript) todo anything, and that can communicate(over websockets) with any other node.

69 / 93

Page 178: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

A New Kind of Web?I The W3C specification defines a JavaScript

endpoint, and is implemented by all majorbrowsers.

I There are endpoints for all majorserver-side technologies, e.g., PHP, Java,.NET, Python, Ruby.

I In conclusion, any browser or server canhave a full-duplex connection with any otherbrowser or server.

I The browser is no longer a just a userinterface. It becomes a node in a network,that can be programmed (in JavaScript) todo anything, and that can communicate(over websockets) with any other node. 69 / 93

Page 179: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

A New Kind of Web?I The W3C specification defines a JavaScript

endpoint, and is implemented by all majorbrowsers.

I There are endpoints for all majorserver-side technologies, e.g., PHP, Java,.NET, Python, Ruby.

I In conclusion, any browser or server canhave a full-duplex connection with any otherbrowser or server.

I The browser is no longer a just a userinterface. It becomes a node in a network,that can be programmed (in JavaScript) todo anything, and that can communicate(over websockets) with any other node. 69 / 93

Page 180: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Section

The Document Object Model, DOM

The Browser Object Model, BOM

The jQuery JavaScript Library

AJAX

Long Polling

WebSocket

The Knockout JavaScript Framework

70 / 93

Page 181: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Reminder: The MVVM PatternI The MVVM pattern

intoduces a client-sidemodel which reflects theserver-side model and isresponsible for notifyingthe view of updates.

I The server-side view isrelieved from creating theHTML. There will not bePHP in the HTML files!

I Also, network communication is reduced,since only model updates are fetched fromthe server. There is no need to reload theentire web page at each user action.

71 / 93

Page 182: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Reminder: The MVVM PatternI The MVVM pattern

intoduces a client-sidemodel which reflects theserver-side model and isresponsible for notifyingthe view of updates.

I The server-side view isrelieved from creating theHTML. There will not bePHP in the HTML files!

I Also, network communication is reduced,since only model updates are fetched fromthe server. There is no need to reload theentire web page at each user action. 71 / 93

Page 183: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Reminder: The MVVM PatternI The MVVM pattern

intoduces a client-sidemodel which reflects theserver-side model and isresponsible for notifyingthe view of updates.

I The server-side view isrelieved from creating theHTML. There will not bePHP in the HTML files!

I Also, network communication is reduced,since only model updates are fetched fromthe server. There is no need to reload theentire web page at each user action. 71 / 93

Page 184: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

MVVM JavaScript FrameworksI The code for implementing the Observer pattern to

have the view reflect changes in the viewmodel (andviewmodel reflect changes in the view), will be thesame for more or less all applications.

I Also the code for viewmodel-to-servercommunication will be quite similar in allapplications.

I This calls for a client-side framework, since we donot want to rewrite the same code for each newapplication. This is exactly the purpose of Knockout.

I There are also many alternative frameworks,perhaps the most commonly used is Backbone.Backbone is more used and more powerful thanKnockout, but too complicated for this course.

72 / 93

Page 185: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

MVVM JavaScript FrameworksI The code for implementing the Observer pattern to

have the view reflect changes in the viewmodel (andviewmodel reflect changes in the view), will be thesame for more or less all applications.

I Also the code for viewmodel-to-servercommunication will be quite similar in allapplications.

I This calls for a client-side framework, since we donot want to rewrite the same code for each newapplication. This is exactly the purpose of Knockout.

I There are also many alternative frameworks,perhaps the most commonly used is Backbone.Backbone is more used and more powerful thanKnockout, but too complicated for this course.

72 / 93

Page 186: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

MVVM JavaScript FrameworksI The code for implementing the Observer pattern to

have the view reflect changes in the viewmodel (andviewmodel reflect changes in the view), will be thesame for more or less all applications.

I Also the code for viewmodel-to-servercommunication will be quite similar in allapplications.

I This calls for a client-side framework, since we donot want to rewrite the same code for each newapplication. This is exactly the purpose of Knockout.

I There are also many alternative frameworks,perhaps the most commonly used is Backbone.Backbone is more used and more powerful thanKnockout, but too complicated for this course.

72 / 93

Page 187: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

MVVM JavaScript FrameworksI The code for implementing the Observer pattern to

have the view reflect changes in the viewmodel (andviewmodel reflect changes in the view), will be thesame for more or less all applications.

I Also the code for viewmodel-to-servercommunication will be quite similar in allapplications.

I This calls for a client-side framework, since we donot want to rewrite the same code for each newapplication. This is exactly the purpose of Knockout.

I There are also many alternative frameworks,perhaps the most commonly used is Backbone.Backbone is more used and more powerful thanKnockout, but too complicated for this course.

72 / 93

Page 188: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Knockout JavaScriptFramework

I Like jQuery, Knockout is a JavaScript file the can belinked from a CDN, for example:<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.1.0/knockout-min.js">

</script>

I Knockout should be used together with jQuery,which handles low-level DOM interaction.

I Knockout implements the MVVM pattern, bymanaging View-to-Viewmodel bindings.

I The following slides contain a brief intro-duction to Knockout. For a more extensive guide, seehttp://knockoutjs.com/documentation/introduction.html

73 / 93

Page 189: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Knockout JavaScriptFramework

I Like jQuery, Knockout is a JavaScript file the can belinked from a CDN, for example:<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.1.0/knockout-min.js">

</script>

I Knockout should be used together with jQuery,which handles low-level DOM interaction.

I Knockout implements the MVVM pattern, bymanaging View-to-Viewmodel bindings.

I The following slides contain a brief intro-duction to Knockout. For a more extensive guide, seehttp://knockoutjs.com/documentation/introduction.html

73 / 93

Page 190: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Knockout JavaScriptFramework

I Like jQuery, Knockout is a JavaScript file the can belinked from a CDN, for example:<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.1.0/knockout-min.js">

</script>

I Knockout should be used together with jQuery,which handles low-level DOM interaction.

I Knockout implements the MVVM pattern, bymanaging View-to-Viewmodel bindings.

I The following slides contain a brief intro-duction to Knockout. For a more extensive guide, seehttp://knockoutjs.com/documentation/introduction.html

73 / 93

Page 191: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Knockout JavaScriptFramework

I Like jQuery, Knockout is a JavaScript file the can belinked from a CDN, for example:<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.1.0/knockout-min.js">

</script>

I Knockout should be used together with jQuery,which handles low-level DOM interaction.

I Knockout implements the MVVM pattern, bymanaging View-to-Viewmodel bindings.

I The following slides contain a brief intro-duction to Knockout. For a more extensive guide, seehttp://knockoutjs.com/documentation/introduction.html

73 / 93

Page 192: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Chat ApplicationI To illustrate this Knockout

tutorial, we will use the chatapplication.

I We will create a viewmodel thatholds the current conversation.

I The view shall be updated assoon as the viewmodel changesstate.

I The viewmodel can changestate either because the userwrote an entry or becauseanother user wrote an entry,which was loaded from theserver to this user’s viewmodel.

74 / 93

Page 193: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Chat ApplicationI To illustrate this Knockout

tutorial, we will use the chatapplication.

I We will create a viewmodel thatholds the current conversation.

I The view shall be updated assoon as the viewmodel changesstate.

I The viewmodel can changestate either because the userwrote an entry or becauseanother user wrote an entry,which was loaded from theserver to this user’s viewmodel.

74 / 93

Page 194: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Chat ApplicationI To illustrate this Knockout

tutorial, we will use the chatapplication.

I We will create a viewmodel thatholds the current conversation.

I The view shall be updated assoon as the viewmodel changesstate.

I The viewmodel can changestate either because the userwrote an entry or becauseanother user wrote an entry,which was loaded from theserver to this user’s viewmodel.

74 / 93

Page 195: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Chat ApplicationI To illustrate this Knockout

tutorial, we will use the chatapplication.

I We will create a viewmodel thatholds the current conversation.

I The view shall be updated assoon as the viewmodel changesstate.

I The viewmodel can changestate either because the userwrote an entry or becauseanother user wrote an entry,which was loaded from theserver to this user’s viewmodel.

74 / 93

Page 196: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Knockout ViewmodelI The viewmodel is an ordinary JavaScript

object, but to make use of Knockout’sviewmodel-to-view binding (observerpattern), the properties must be declaredas observables.function Person(name, age) {var self = this;self.name = ko.observable(name);self.age = ko.observable(age);

}

I To read or write a property value, call theproperty as a function.var olle = new Person("Olle", 35);olle.name(); // Returns "Olle"olle.age(36); // Sets the age to 36.

75 / 93

Page 197: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Knockout ViewmodelI The viewmodel is an ordinary JavaScript

object, but to make use of Knockout’sviewmodel-to-view binding (observerpattern), the properties must be declaredas observables.function Person(name, age) {var self = this;self.name = ko.observable(name);self.age = ko.observable(age);

}

I To read or write a property value, call theproperty as a function.var olle = new Person("Olle", 35);olle.name(); // Returns "Olle"olle.age(36); // Sets the age to 36.

75 / 93

Page 198: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Chat Application’s Viewmodel

I The Chat’s viewmodel has two objects.I EntryToAdd represents a newly written

entry that shall be sent to the server.

I Conversation represents the entireconversation.

I The EntryToAdd object has twoproperties, nickName and msgfunction EntryToAdd() {

var self = this;self.nickName = ko.observable();self.msg = ko.observable("");...

}

76 / 93

Page 199: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Chat Application’s Viewmodel

I The Chat’s viewmodel has two objects.I EntryToAdd represents a newly written

entry that shall be sent to the server.I Conversation represents the entire

conversation.

I The EntryToAdd object has twoproperties, nickName and msgfunction EntryToAdd() {

var self = this;self.nickName = ko.observable();self.msg = ko.observable("");...

}

76 / 93

Page 200: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Chat Application’s Viewmodel

I The Chat’s viewmodel has two objects.I EntryToAdd represents a newly written

entry that shall be sent to the server.I Conversation represents the entire

conversation.

I The EntryToAdd object has twoproperties, nickName and msgfunction EntryToAdd() {

var self = this;self.nickName = ko.observable();self.msg = ko.observable("");...

}

76 / 93

Page 201: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Chat Application’s Viewmodel

I The Chat’s viewmodel has two objects.I EntryToAdd represents a newly written

entry that shall be sent to the server.I Conversation represents the entire

conversation.

I The EntryToAdd object has twoproperties, nickName and msgfunction EntryToAdd() {

var self = this;self.nickName = ko.observable();self.msg = ko.observable("");...

}

76 / 93

Page 202: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Chat Application’s Viewmodel(Cont’d)var entryToAdd = new EntryToAdd();ko.applyBindings(entryToAdd,

document.getElementById(’new-entry’));

I The viewmodel must be registered with Knockout toenable notifying the observers in the view.

I After a JavaScript object has been registered withknockout using the function applyBindings, itwill always have the same state as the elements inthe DOM.

I When the object changes state, the DOM willchange state. When the DOM changes state,the object will change state.

I The second parameter tells to which element in theDOM entryToAdd shall be bound. There canonly be at most one bound object per element.

77 / 93

Page 203: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Chat Application’s Viewmodel(Cont’d)var entryToAdd = new EntryToAdd();ko.applyBindings(entryToAdd,

document.getElementById(’new-entry’));

I The viewmodel must be registered with Knockout toenable notifying the observers in the view.

I After a JavaScript object has been registered withknockout using the function applyBindings, itwill always have the same state as the elements inthe DOM.

I When the object changes state, the DOM willchange state. When the DOM changes state,the object will change state.

I The second parameter tells to which element in theDOM entryToAdd shall be bound. There canonly be at most one bound object per element.

77 / 93

Page 204: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Chat Application’s Viewmodel(Cont’d)var entryToAdd = new EntryToAdd();ko.applyBindings(entryToAdd,

document.getElementById(’new-entry’));

I The viewmodel must be registered with Knockout toenable notifying the observers in the view.

I After a JavaScript object has been registered withknockout using the function applyBindings, itwill always have the same state as the elements inthe DOM.

I When the object changes state, the DOM willchange state. When the DOM changes state,the object will change state.

I The second parameter tells to which element in theDOM entryToAdd shall be bound. There canonly be at most one bound object per element. 77 / 93

Page 205: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Chat Application’s Viewmodel(Cont’d)var entryToAdd = new EntryToAdd();ko.applyBindings(entryToAdd,

document.getElementById(’new-entry’));

I The viewmodel must be registered with Knockout toenable notifying the observers in the view.

I After a JavaScript object has been registered withknockout using the function applyBindings, itwill always have the same state as the elements inthe DOM.

I When the object changes state, the DOM willchange state. When the DOM changes state,the object will change state.

I The second parameter tells to which element in theDOM entryToAdd shall be bound. There canonly be at most one bound object per element. 77 / 93

Page 206: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Data BindingsI A HTML element in the view is connected to a

viewmodel property with a binding.

I A binding is declared by adding the data-bindattribute to the HTML element.

I There are many different types of bindings, like:

text The property value is inserted to the HTMLelement.The message is:<span data-bind="text: msg"></span>

visible Decides if the element is rendered.<div data-bind=

"visible: shouldShowMessage">

css Adds or removes CSS classes. The followingbinding adds the class warning if theprofit property is negative.<div data-bind=

"css: {warning: profit() < 0 }">

78 / 93

Page 207: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Data BindingsI A HTML element in the view is connected to a

viewmodel property with a binding.

I A binding is declared by adding the data-bindattribute to the HTML element.

I There are many different types of bindings, like:

text The property value is inserted to the HTMLelement.The message is:<span data-bind="text: msg"></span>

visible Decides if the element is rendered.<div data-bind=

"visible: shouldShowMessage">

css Adds or removes CSS classes. The followingbinding adds the class warning if theprofit property is negative.<div data-bind=

"css: {warning: profit() < 0 }">

78 / 93

Page 208: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Data BindingsI A HTML element in the view is connected to a

viewmodel property with a binding.

I A binding is declared by adding the data-bindattribute to the HTML element.

I There are many different types of bindings, like:text The property value is inserted to the HTML

element.The message is:<span data-bind="text: msg"></span>

visible Decides if the element is rendered.<div data-bind=

"visible: shouldShowMessage">

css Adds or removes CSS classes. The followingbinding adds the class warning if theprofit property is negative.<div data-bind=

"css: {warning: profit() < 0 }">

78 / 93

Page 209: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Data BindingsI A HTML element in the view is connected to a

viewmodel property with a binding.

I A binding is declared by adding the data-bindattribute to the HTML element.

I There are many different types of bindings, like:text The property value is inserted to the HTML

element.The message is:<span data-bind="text: msg"></span>

visible Decides if the element is rendered.<div data-bind=

"visible: shouldShowMessage">

css Adds or removes CSS classes. The followingbinding adds the class warning if theprofit property is negative.<div data-bind=

"css: {warning: profit() < 0 }">

78 / 93

Page 210: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Data BindingsI A HTML element in the view is connected to a

viewmodel property with a binding.

I A binding is declared by adding the data-bindattribute to the HTML element.

I There are many different types of bindings, like:text The property value is inserted to the HTML

element.The message is:<span data-bind="text: msg"></span>

visible Decides if the element is rendered.<div data-bind=

"visible: shouldShowMessage">

css Adds or removes CSS classes. The followingbinding adds the class warning if theprofit property is negative.<div data-bind=

"css: {warning: profit() < 0 }"> 78 / 93

Page 211: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Data BindingsI A HTML element in the view is connected to a

viewmodel property with a binding.

I A binding is declared by adding the data-bindattribute to the HTML element.

I There are many different types of bindings, like:text The property value is inserted to the HTML

element.The message is:<span data-bind="text: msg"></span>

visible Decides if the element is rendered.<div data-bind=

"visible: shouldShowMessage">

css Adds or removes CSS classes. The followingbinding adds the class warning if theprofit property is negative.<div data-bind=

"css: {warning: profit() < 0 }"> 78 / 93

Page 212: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Form Field BindingsThere are also bindings for form elements, such as:

click Specifies a method that is called when theelement is clicked.<button data-bind=

"click: clickHandler">Click me</button>

textInput Binds a text field or text area to a viewmodelproperty<input type="text"

data-bind="textInput: username"/>

enable The element is enabled only when the valueis trueYour cellphone number:<input type=’text’ data-bind=

"textInput: cellphoneNumber, enable: hasCellphone"/>

79 / 93

Page 213: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Form Field BindingsThere are also bindings for form elements, such as:

click Specifies a method that is called when theelement is clicked.<button data-bind=

"click: clickHandler">Click me</button>

textInput Binds a text field or text area to a viewmodelproperty<input type="text"

data-bind="textInput: username"/>

enable The element is enabled only when the valueis trueYour cellphone number:<input type=’text’ data-bind=

"textInput: cellphoneNumber, enable: hasCellphone"/>

79 / 93

Page 214: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Form Field BindingsThere are also bindings for form elements, such as:

click Specifies a method that is called when theelement is clicked.<button data-bind=

"click: clickHandler">Click me</button>

textInput Binds a text field or text area to a viewmodelproperty<input type="text"

data-bind="textInput: username"/>

enable The element is enabled only when the valueis trueYour cellphone number:<input type=’text’ data-bind=

"textInput: cellphoneNumber, enable: hasCellphone"/>

79 / 93

Page 215: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Chat Message Data-BindingsI Now let us create the data bindings

for the nick name text and msg textarea.<label id="nickNameLabel" for="entry">

<span data-bind="text: nickName"></span>says:

</label>...<textarea id= "entry" rows = 5

data-bind="textInput: msg"placeholder="Write entry here.">

</textarea>

I Now the nickname element and thenickName property in theEntryToAdd object will alwayshave the same value.

I Also, the text in the textarea will always be the sameas the value of the msg property.

80 / 93

Page 216: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Chat Message Data-BindingsI Now let us create the data bindings

for the nick name text and msg textarea.<label id="nickNameLabel" for="entry">

<span data-bind="text: nickName"></span>says:

</label>...<textarea id= "entry" rows = 5

data-bind="textInput: msg"placeholder="Write entry here.">

</textarea>

I Now the nickname element and thenickName property in theEntryToAdd object will alwayshave the same value.

I Also, the text in the textarea will always be the sameas the value of the msg property.

80 / 93

Page 217: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Chat Message Data-BindingsI Now let us create the data bindings

for the nick name text and msg textarea.<label id="nickNameLabel" for="entry">

<span data-bind="text: nickName"></span>says:

</label>...<textarea id= "entry" rows = 5

data-bind="textInput: msg"placeholder="Write entry here.">

</textarea>

I Now the nickname element and thenickName property in theEntryToAdd object will alwayshave the same value.

I Also, the text in the textarea will always be the sameas the value of the msg property.

80 / 93

Page 218: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Click Data-Bindings

<button data-bind="click: sendEntry">Send

</button>

I Then let us create the data-binding for the Send button.

I Here we specified that thesendEntry method is calledwhen the user clicks the button.

81 / 93

Page 219: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Click Data-Bindings

<button data-bind="click: sendEntry">Send

</button>

I Then let us create the data-binding for the Send button.

I Here we specified that thesendEntry method is calledwhen the user clicks the button.

81 / 93

Page 220: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The sendEntry Method1 self.sendEntry = function () {2 if (self.msg() !== "") {3 $.post(writeUrl,4 "msg=" + ko.toJS(self.msg));5 self.msg("");6 }7 };

I Line 2 checks that the user has typed a message.

I Lines 3-4 sends the new entry to the server in aHTTP post request.

I The call to ko.toJS on line 4 converts themessage to plain JavaScript, instead of anobservable.

I Line 5 clears the text area.

82 / 93

Page 221: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The sendEntry Method1 self.sendEntry = function () {2 if (self.msg() !== "") {3 $.post(writeUrl,4 "msg=" + ko.toJS(self.msg));5 self.msg("");6 }7 };

I Line 2 checks that the user has typed a message.

I Lines 3-4 sends the new entry to the server in aHTTP post request.

I The call to ko.toJS on line 4 converts themessage to plain JavaScript, instead of anobservable.

I Line 5 clears the text area.

82 / 93

Page 222: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The sendEntry Method1 self.sendEntry = function () {2 if (self.msg() !== "") {3 $.post(writeUrl,4 "msg=" + ko.toJS(self.msg));5 self.msg("");6 }7 };

I Line 2 checks that the user has typed a message.

I Lines 3-4 sends the new entry to the server in aHTTP post request.

I The call to ko.toJS on line 4 converts themessage to plain JavaScript, instead of anobservable.

I Line 5 clears the text area.

82 / 93

Page 223: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The sendEntry Method1 self.sendEntry = function () {2 if (self.msg() !== "") {3 $.post(writeUrl,4 "msg=" + ko.toJS(self.msg));5 self.msg("");6 }7 };

I Line 2 checks that the user has typed a message.

I Lines 3-4 sends the new entry to the server in aHTTP post request.

I The call to ko.toJS on line 4 converts themessage to plain JavaScript, instead of anobservable.

I Line 5 clears the text area.

82 / 93

Page 224: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Read Nickname From ServerI One question remains, how did the nickname show

up correctly in the view? Note that it is not insertedin php code on the server (very good!):<label id="nickNameLabel" for="entry">

<span data-bind="text: nickName"></span>says:

</label>

I The answer is that the nickname was read in anextra AJAX call from the EntryToAdd constructor.function EntryToAdd() {

var self = this;self.nickName = ko.observable();...$.getJSON(nickNameUrl, function (username) {

self.nickName(username);});

}

83 / 93

Page 225: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Read Nickname From ServerI One question remains, how did the nickname show

up correctly in the view? Note that it is not insertedin php code on the server (very good!):<label id="nickNameLabel" for="entry">

<span data-bind="text: nickName"></span>says:

</label>

I The answer is that the nickname was read in anextra AJAX call from the EntryToAdd constructor.function EntryToAdd() {

var self = this;self.nickName = ko.observable();...$.getJSON(nickNameUrl, function (username) {

self.nickName(username);});

}

83 / 93

Page 226: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Read Nickname From Server(Cont’d)

I The ajax call on the previous slide is handled by theGetUsername request handler (code below is notcomplete).class GetUsername extends AbstractRequestHandler {

protected function doExecute() {$this->addVariable(’jsonData’,

$contr->getUsername());return ’json-view’;

}

}

I json-view.php just echos the value of$jsonData.echo \json_encode($jsonData);

84 / 93

Page 227: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Read Nickname From Server(Cont’d)

I The ajax call on the previous slide is handled by theGetUsername request handler (code below is notcomplete).class GetUsername extends AbstractRequestHandler {

protected function doExecute() {$this->addVariable(’jsonData’,

$contr->getUsername());return ’json-view’;

}

}

I json-view.php just echos the value of$jsonData.echo \json_encode($jsonData);

84 / 93

Page 228: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Conversation object inthe viewmodel

I Now we have covered everything in theEntryToAdd object in the viewmodel.

I There is one more object in the viewmodel,Conversation, which contains theentire chat conversation.

I Conversation has a property,entries that holds an array of allconversation entries.

I To understand how that works, we mustlook at how knockout binds arrays toelements in the DOM.

85 / 93

Page 229: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Conversation object inthe viewmodel

I Now we have covered everything in theEntryToAdd object in the viewmodel.

I There is one more object in the viewmodel,Conversation, which contains theentire chat conversation.

I Conversation has a property,entries that holds an array of allconversation entries.

I To understand how that works, we mustlook at how knockout binds arrays toelements in the DOM.

85 / 93

Page 230: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Conversation object inthe viewmodel

I Now we have covered everything in theEntryToAdd object in the viewmodel.

I There is one more object in the viewmodel,Conversation, which contains theentire chat conversation.

I Conversation has a property,entries that holds an array of allconversation entries.

I To understand how that works, we mustlook at how knockout binds arrays toelements in the DOM.

85 / 93

Page 231: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Conversation object inthe viewmodel

I Now we have covered everything in theEntryToAdd object in the viewmodel.

I There is one more object in the viewmodel,Conversation, which contains theentire chat conversation.

I Conversation has a property,entries that holds an array of allconversation entries.

I To understand how that works, we mustlook at how knockout binds arrays toelements in the DOM.

85 / 93

Page 232: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Observable Arrays

I To observe an array, use observableArray.

var myObservableArray = ko.observableArray();

I The entries property in Conversation is anobservableArray and holds an array of objectshaving the two properties nickName and msg

function Conversation(entryToAdd) {var self = this;...self.entries = ko.observableArray();...

}

86 / 93

Page 233: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Observable Arrays

I To observe an array, use observableArray.

var myObservableArray = ko.observableArray();

I The entries property in Conversation is anobservableArray and holds an array of objectshaving the two properties nickName and msg

function Conversation(entryToAdd) {var self = this;...self.entries = ko.observableArray();...

}

86 / 93

Page 234: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Flow Control Data-Bindings

I When binding entries to the DOM, we must usethe flow control data bindings if and foreach.Let’s first have a look at those.

I foreach binds each element in an array to theDOM.

I Whenever elements are added, removed, orre-ordered in a bound observable array, the DOMwill be updated to reflect the new array contents.

87 / 93

Page 235: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Flow Control Data-Bindings

I When binding entries to the DOM, we must usethe flow control data bindings if and foreach.Let’s first have a look at those.

I foreach binds each element in an array to theDOM.

I Whenever elements are added, removed, orre-ordered in a bound observable array, the DOMwill be updated to reflect the new array contents.

87 / 93

Page 236: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Flow Control Data-Bindings

I When binding entries to the DOM, we must usethe flow control data bindings if and foreach.Let’s first have a look at those.

I foreach binds each element in an array to theDOM.

I Whenever elements are added, removed, orre-ordered in a bound observable array, the DOMwill be updated to reflect the new array contents.

87 / 93

Page 237: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

foreach Data-Binding (Cont’d)Assuming people is a JavaScript array of objects withfirstName and lastName properties, the followinggenerates a table with one object per row.

<table><thead>

<tr><th>First name</th><th>Last name</th></tr>

</thead><tbody data-bind="foreach: people">

<tr><td data-bind="text: firstName"></td><td data-bind="text: lastName"></td>

</tr></tbody>

</table>

88 / 93

Page 238: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

foreach Data-Binding (Cont’d)I The current array element is referred using $data

<ul data-bind="foreach: months"><li>

<span data-bind="text: $data"></span></li>

</ul>

I as gives an alias to the current array element.<ul data-bind=

"foreach: { data: categories, as: ’category’ }"><li>

<ul data-bind="foreach: { data: items, as: ’item’ }"><li>

<span data-bind="text: category.name"></span>:<span data-bind="text: item.name"></span>

</li></ul>

</li></ul>

89 / 93

Page 239: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

foreach Data-Binding (Cont’d)I The current array element is referred using $data

<ul data-bind="foreach: months"><li>

<span data-bind="text: $data"></span></li>

</ul>

I as gives an alias to the current array element.<ul data-bind=

"foreach: { data: categories, as: ’category’ }"><li>

<ul data-bind="foreach: { data: items, as: ’item’ }"><li>

<span data-bind="text: category.name"></span>:<span data-bind="text: item.name"></span>

</li></ul>

</li></ul>

89 / 93

Page 240: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Containerless Control Flow SyntaxI If there is no containing element for the

data-binding, use the containerless syntax, basedon HTML comment tags.<!-- ko foreach: {data:items, as:’item’} -->

<p><span data-bind="text:item.price"></span>

</p><!-- /ko -->

I An if data-binding displays the enclosed elementsonly if the condition is true.<!-- ko if: item.isOffer --><p>

Offer!</p>

<!-- /ko -->

90 / 93

Page 241: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Containerless Control Flow SyntaxI If there is no containing element for the

data-binding, use the containerless syntax, basedon HTML comment tags.<!-- ko foreach: {data:items, as:’item’} -->

<p><span data-bind="text:item.price"></span>

</p><!-- /ko -->

I An if data-binding displays the enclosed elementsonly if the condition is true.<!-- ko if: item.isOffer --><p>

Offer!</p>

<!-- /ko -->

90 / 93

Page 242: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Conversation Data-BindingI Now we can create the data binding for the

conversation part of the chat application (code is notcomplete).

I The inner loop is needed for multi-line messages.

<!-- ko foreach: {data: entries, as: ’entry’} --><p>

<span data-bind=’text: entry.nickName’></span>:</p><!-- ko foreach: entry.msg -->

<p><span data-bind=’text: $data’></span>

</p><!-- /ko --><!-- ko if: entry.iWroteThisEntry -->

<p><button data-bind=

’click: $parent.deleteEntry’>Delete

</button></p>

<!-- /ko --><!-- /ko -->

91 / 93

Page 243: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

The Conversation Data-BindingI Now we can create the data binding for the

conversation part of the chat application (code is notcomplete).

I The inner loop is needed for multi-line messages.

<!-- ko foreach: {data: entries, as: ’entry’} --><p>

<span data-bind=’text: entry.nickName’></span>:</p><!-- ko foreach: entry.msg -->

<p><span data-bind=’text: $data’></span>

</p><!-- /ko --><!-- ko if: entry.iWroteThisEntry -->

<p><button data-bind=

’click: $parent.deleteEntry’>Delete

</button></p>

<!-- /ko --><!-- /ko -->

91 / 93

Page 244: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

No PHP! (Almost)

I That was all, now we have seen anoverview of some features in Knockout, andalso created the chat application.

I As a result, there is now no PHP code leftin the html files!

I Except for including fragments and creatinglink paths.

92 / 93

Page 245: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

No PHP! (Almost)

I That was all, now we have seen anoverview of some features in Knockout, andalso created the chat application.

I As a result, there is now no PHP code leftin the html files!

I Except for including fragments and creatinglink paths.

92 / 93

Page 246: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

No PHP! (Almost)

I That was all, now we have seen anoverview of some features in Knockout, andalso created the chat application.

I As a result, there is now no PHP code leftin the html files!

I Except for including fragments and creatinglink paths.

92 / 93

Page 247: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Without JavaScript frameworkWithout a JavaScript framework that handlesviewmodel-to-DOM bindings, where would we store thenickname and chat conversation? There are three options,each with serious drawbacks.

1. Write the JavaScript code that is now in theframework. This means quite a lot of quite trickyhandling of the DOM, knockout.js containsthousands of lines of JavaScript code.

2. Do not create a viewmodel, but store the data only inthe DOM. This is the case in the chat examplewithout knockout on the course web. Even for thissmall program it means quite a lot of searchingthrough HTML elements and parsing string.

3. Store data only on the server. This means there isno JavaScript client at all, and we are back toreloading the entire page whenever the user doessomething.

93 / 93

Page 248: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Without JavaScript frameworkWithout a JavaScript framework that handlesviewmodel-to-DOM bindings, where would we store thenickname and chat conversation? There are three options,each with serious drawbacks.

1. Write the JavaScript code that is now in theframework. This means quite a lot of quite trickyhandling of the DOM, knockout.js containsthousands of lines of JavaScript code.

2. Do not create a viewmodel, but store the data only inthe DOM. This is the case in the chat examplewithout knockout on the course web. Even for thissmall program it means quite a lot of searchingthrough HTML elements and parsing string.

3. Store data only on the server. This means there isno JavaScript client at all, and we are back toreloading the entire page whenever the user doessomething.

93 / 93

Page 249: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Without JavaScript frameworkWithout a JavaScript framework that handlesviewmodel-to-DOM bindings, where would we store thenickname and chat conversation? There are three options,each with serious drawbacks.

1. Write the JavaScript code that is now in theframework. This means quite a lot of quite trickyhandling of the DOM, knockout.js containsthousands of lines of JavaScript code.

2. Do not create a viewmodel, but store the data only inthe DOM. This is the case in the chat examplewithout knockout on the course web. Even for thissmall program it means quite a lot of searchingthrough HTML elements and parsing string.

3. Store data only on the server. This means there isno JavaScript client at all, and we are back toreloading the entire page whenever the user doessomething.

93 / 93

Page 250: Using JavaScript for Client-Side Behavior - Internet ... · Using JavaScript for Client-Side Behavior - Internet ... ... bom ajax

Using JavaScript

DOM

BOM

jQuery

AJAX

Long Polling

WebSocket

Knockout

Without JavaScript frameworkWithout a JavaScript framework that handlesviewmodel-to-DOM bindings, where would we store thenickname and chat conversation? There are three options,each with serious drawbacks.

1. Write the JavaScript code that is now in theframework. This means quite a lot of quite trickyhandling of the DOM, knockout.js containsthousands of lines of JavaScript code.

2. Do not create a viewmodel, but store the data only inthe DOM. This is the case in the chat examplewithout knockout on the course web. Even for thissmall program it means quite a lot of searchingthrough HTML elements and parsing string.

3. Store data only on the server. This means there isno JavaScript client at all, and we are back toreloading the entire page whenever the user doessomething.

93 / 93