SlideShare a Scribd company logo
1 of 31
Download to read offline
Dienstag, 11. Februar 14
PRIMARY USE CASE

Dienstag, 11. Februar 14
BROWSER FACADE
App code

Dienstag, 11. Februar 14

use

jQuery

use

Browser API
Browser API
Browser API
Browser API
BROWSER FACADE
• smooth out browser incompatibilities
• shield from verbose W3C DOM API
• countless utilities for convenient development

Dienstag, 11. Februar 14
JQUERY IS A LIBRARY
• ultimate productivity boost
• no application lifecycle provided
• no MVC infrastructure provided
• no component model (jQuery UI has)
• lacks a decent object oriented approach
• easy to create code which is hard to maintain
• jQuery code sprinkled all over markup
Dienstag, 11. Februar 14
jQuery - core browser facade
jQuery UI - User Interface components
jQuery mobile - mobile UI framework
QUnit - unit/component testing framework
Sizzle - CSS selector engine
Dienstag, 11. Februar 14
101: PROBLEM SPACES
• selecting DOM elements
• traversing the DOM
• manipulating DOM elements
• setting CSS properties
• handling browser events
• browser networking

Dienstag, 11. Februar 14
BASIC IDEA

Dienstag, 11. Februar 14
101: BASIC WORKFLOW

1. select (query) elements
2. operate on selection

Dienstag, 11. Februar 14
101: SELECTORS
support for CSS3 selectors and more
// select an element by id
$("#menu").addClass("menu-theme-dark");
// select elements by class
$(".menu-item").removeClass("active");
// select elements by tag name
$("body").removeClass("small-screen");
// a list items with a give class in a given anchestor
$("#menu li.active").removeClass("active");
// all elements with a given attr in a given anchestor
$("#menu [data-action]").css("border-top", "1px solid red");

Dienstag, 11. Februar 14
101: SELECTORS
#menu .item

<ul id=“menu“>
<li class=“item“></li>
<li class=“item“></li>
</ul>

.item:first-child

<ul id=“menu“>
<li class=“item“></li>
<li class=“item“></li>
</ul>

.item.selected

<ul id=“menu“>
<li class=“item selected“></li>
<li class=“item“></li>
</ul>

[data-action]

<button data-action=“edit“>edit</button>
<i data-action=“del“>delete</i>

Dienstag, 11. Februar 14
101: SELECTORS
#menu li

#menu > li

Dienstag, 11. Februar 14

<ul id=“menu“>
<li class=“item“>
<ul>
<li></li>
</ul>
</li>
</ul>
<ul id=“menu“>
<li class=“item“>
<ul>
<li></li>
</ul>
</li>
</ul>
101: SELECTORS
#menu li, .list li

<ul id=“menu“>
<li class=“item“></li>
</ul>
<ul class=“list“>
<li></li>
</ul>

tr:hover td

Dienstag, 11. Februar 14

<tr>
<td></td>
<td></td>
<td></td>
</tr>
101: FLUID API
fluid API style allows to chain
operations on a given selection
$(".menu-item")
.removeClass("active")
.addClass("inactive ")
.css("padding-left", "0px")
.find(".trigger")
.click(function(ev) {
...
})
.each(function () {
...
});

Dienstag, 11. Februar 14
101: FLUID API
fluid API style allows to chain
operations on a given selection
$(".menu-item")
.removeClass("active")
.addClass("inactive ")
.css("padding-left", "0px")
.find(".trigger")
.click(function(ev) {
// spaghetti carbonara?
})
.each(function () {
// spaghetti napoli?
});

Dienstag, 11. Februar 14
EVENTS

Dienstag, 11. Februar 14
101: EVENTS
trigger.on("mouseover", function (ev) {
// fired on mouse over the trigger
});
trigger.click(function (ev) {
// short-cut for common events
});
sidebar.on("click", ".menu a", function () {
// handle all menu items with a single handler
});
sidebar.on("click", "tr td:first-child", function () {
// handle all clicks on the first cell of any row
});

Dienstag, 11. Februar 14
101: CATCHING BUBBLING
EVENTS
Hans
Vreni
Karl

Meier
Huber
Wehrli

1967
1982
1912

m
w
m

e
e
e

-

<button data-action=“remove-row“>-</button>
$("#data-table").click(function(ev) {

});
Dienstag, 11. Februar 14

var action = $(ev.target).data("action");
if (action === "remove-row") {
var personId = $(ev.target).closest(„[data-id]“];
...
} else if (action === "edit-row") {
...
}
101: CUSTOM EVENTS
// jQuery lets you trigger events
$("#btn").trigger("click");

Dienstag, 11. Februar 14
101: CUSTOM EVENTS
// jQuery lets you trigger events
$("#btn").trigger("click");
// custom events are allowed; so...
container.on("msg:myApp", function (ev, data) {
// update UI
});

Dienstag, 11. Februar 14
101: CUSTOM EVENTS
// jQuery lets you trigger events
$("#btn").trigger("click");
// custom events are allowed; so...
container.on("msg:myApp", function (ev, data) {
// update UI
});
btn.click(function (ev) {
btn.trigger("msg:myApp", {
name: "age",
val: 42,
type: "update"
});
});

Dienstag, 11. Februar 14
AJAX

Dienstag, 11. Februar 14
101: AJAX
$.ajax({
url: "/api/order",
type: "PUT"
data: { userId: 1234, lineItems: lineItems},
dataType: "json"
success: function (data) {
emitEvent("sent-order", data);
},
error: function (jqXhr) {
growl("sending order failed");
}
});

Dienstag, 11. Februar 14

+
101: AJAX CONVENIENCE
// simplified GET requests
$.get("/dashboard", function (htmlOrXmlResponse) {
alert(htmlOrXmlResponse);
});
// POST form data
$.post("/contact",
$("#contact-form").serialize(),
function () {
alert("success");
}
);
// json reponse parsed to js object
$.getJSON("/persons.", function (data) {
alert(data);
});
// load content of url into an element
$("#content").load("partials/dashboard.html");

Dienstag, 11. Februar 14
101: GLOBAL AJAX
var pendingCount = 0;
$(document).ajaxStart(function() {
if (pendingCount === 0) {
$( "#spinner" ).show();
}
pendingCount++;
});
$(document).ajaxComplete(function() {
pendingCount--;
if (pendingCount === 0) {
$( "#spinner" ).hide();
}
});

Dienstag, 11. Februar 14
101: GLOBAL AJAX
/**
* ajaxPrefilter is called for each request processed
* with $.ajax or other jQuery http functions
*/
$.ajaxPrefilter(function(options, origOptions, jqXHR) {
// set the Authorization header for all request
options.headers = {
Authorization: "Basic " + btoa("chopen2013:chopen2013")
};
});

Dienstag, 11. Februar 14
CONVENIENCE

Dienstag, 11. Februar 14
101: CONVENIENCE
// setting removing style classes
$(".item").addClass("myClass");
$(".item").removeClass("myClass");
$(".item").toggleClass("myClass");
// display, hide selected elements
$("#item").show(); $("#item").hide(); $("#item").toggle();
$("#item").fadeIn(); $("#item").fadeOut();

Dienstag, 11. Februar 14
101: EACH
compared to for-loops ,each‘ is slower, but safer
$.each([1,2,3,4,5], function (idx, item) {
trigger.on(„click“, function() {
// use idx and item here with no worries
};
});

var person = { firstName: "Helge", lastName: "Schneider" };
$.each(person, function (key, value) {
// ...
// value is bound to this
});

Dienstag, 11. Februar 14
LUNCH!
Dienstag, 11. Februar 14
EXERCISES

uery/exercises
~/ws/03-jQ
Dienstag, 11. Februar 14

More Related Content

Viewers also liked

Analisis critical heat flux dalam celah sempit rektangular vertikal rev 02
Analisis critical heat flux dalam celah sempit rektangular vertikal rev 02Analisis critical heat flux dalam celah sempit rektangular vertikal rev 02
Analisis critical heat flux dalam celah sempit rektangular vertikal rev 02moh rohmatulloh
 
Core Banking - Management der Kernbank IT
Core Banking - Management der Kernbank ITCore Banking - Management der Kernbank IT
Core Banking - Management der Kernbank ITTorben Haagh
 
Allen M Moore Resume
Allen M  Moore ResumeAllen M  Moore Resume
Allen M Moore ResumeAllen Moore
 
Charlie Hebdo - Edición Especial
Charlie Hebdo - Edición EspecialCharlie Hebdo - Edición Especial
Charlie Hebdo - Edición EspecialEmiliano Arnáez
 
Catastro herramienta gestionmunicipal
Catastro herramienta gestionmunicipalCatastro herramienta gestionmunicipal
Catastro herramienta gestionmunicipalGiovanny González
 
Funcion supervisora
Funcion supervisoraFuncion supervisora
Funcion supervisorajarape
 
Pasos de instalacion de windows 7, windows 8 y ubuntu
Pasos de instalacion de windows 7, windows 8 y ubuntuPasos de instalacion de windows 7, windows 8 y ubuntu
Pasos de instalacion de windows 7, windows 8 y ubuntuJose Luis Quispe OficialFb
 
Avaya Sip Within Your Enterprise
Avaya   Sip Within Your EnterpriseAvaya   Sip Within Your Enterprise
Avaya Sip Within Your Enterprisehypknight
 
Informe de Gestion Enero 2008 a Junio 2009 CGQ
Informe de Gestion Enero 2008 a Junio 2009 CGQInforme de Gestion Enero 2008 a Junio 2009 CGQ
Informe de Gestion Enero 2008 a Junio 2009 CGQcontraloriaquindio
 
Marcadores discursivos
Marcadores discursivosMarcadores discursivos
Marcadores discursivosp_queipo
 
Mgt 4301 ppt ch03
Mgt 4301 ppt ch03Mgt 4301 ppt ch03
Mgt 4301 ppt ch03youss89
 
Factores de riesgo para enterocolitis necrosante en una unidad de cuidados in...
Factores de riesgo para enterocolitis necrosante en una unidad de cuidados in...Factores de riesgo para enterocolitis necrosante en una unidad de cuidados in...
Factores de riesgo para enterocolitis necrosante en una unidad de cuidados in...Hospital Pediátrico de Sinaloa
 
Manual de procedimientos
Manual de procedimientosManual de procedimientos
Manual de procedimientosAndyMoBa
 
6 Referral Marketing Best Practices To Turn Customers Into Word-Of-Mouth Mark...
6 Referral Marketing Best Practices To Turn Customers Into Word-Of-Mouth Mark...6 Referral Marketing Best Practices To Turn Customers Into Word-Of-Mouth Mark...
6 Referral Marketing Best Practices To Turn Customers Into Word-Of-Mouth Mark...G3 Communications
 
Qué es filosofía
Qué es filosofíaQué es filosofía
Qué es filosofíaLa Fenech
 
Cloud-powered Continuous Integration and Deployment architectures - Jinesh Varia
Cloud-powered Continuous Integration and Deployment architectures - Jinesh VariaCloud-powered Continuous Integration and Deployment architectures - Jinesh Varia
Cloud-powered Continuous Integration and Deployment architectures - Jinesh VariaAmazon Web Services
 

Viewers also liked (20)

Analisis critical heat flux dalam celah sempit rektangular vertikal rev 02
Analisis critical heat flux dalam celah sempit rektangular vertikal rev 02Analisis critical heat flux dalam celah sempit rektangular vertikal rev 02
Analisis critical heat flux dalam celah sempit rektangular vertikal rev 02
 
Core Banking - Management der Kernbank IT
Core Banking - Management der Kernbank ITCore Banking - Management der Kernbank IT
Core Banking - Management der Kernbank IT
 
Allen M Moore Resume
Allen M  Moore ResumeAllen M  Moore Resume
Allen M Moore Resume
 
Charlie Hebdo - Edición Especial
Charlie Hebdo - Edición EspecialCharlie Hebdo - Edición Especial
Charlie Hebdo - Edición Especial
 
Cash webinar flyer
Cash webinar flyerCash webinar flyer
Cash webinar flyer
 
Catastro herramienta gestionmunicipal
Catastro herramienta gestionmunicipalCatastro herramienta gestionmunicipal
Catastro herramienta gestionmunicipal
 
Common Modes Of Dynamic Behavior
Common Modes Of Dynamic BehaviorCommon Modes Of Dynamic Behavior
Common Modes Of Dynamic Behavior
 
Funcion supervisora
Funcion supervisoraFuncion supervisora
Funcion supervisora
 
Cartel- Fiebre tifoidea
Cartel- Fiebre tifoidea Cartel- Fiebre tifoidea
Cartel- Fiebre tifoidea
 
Pasos de instalacion de windows 7, windows 8 y ubuntu
Pasos de instalacion de windows 7, windows 8 y ubuntuPasos de instalacion de windows 7, windows 8 y ubuntu
Pasos de instalacion de windows 7, windows 8 y ubuntu
 
Avaya Sip Within Your Enterprise
Avaya   Sip Within Your EnterpriseAvaya   Sip Within Your Enterprise
Avaya Sip Within Your Enterprise
 
Informe de Gestion Enero 2008 a Junio 2009 CGQ
Informe de Gestion Enero 2008 a Junio 2009 CGQInforme de Gestion Enero 2008 a Junio 2009 CGQ
Informe de Gestion Enero 2008 a Junio 2009 CGQ
 
Marcadores discursivos
Marcadores discursivosMarcadores discursivos
Marcadores discursivos
 
Mgt 4301 ppt ch03
Mgt 4301 ppt ch03Mgt 4301 ppt ch03
Mgt 4301 ppt ch03
 
QlikView
QlikViewQlikView
QlikView
 
Factores de riesgo para enterocolitis necrosante en una unidad de cuidados in...
Factores de riesgo para enterocolitis necrosante en una unidad de cuidados in...Factores de riesgo para enterocolitis necrosante en una unidad de cuidados in...
Factores de riesgo para enterocolitis necrosante en una unidad de cuidados in...
 
Manual de procedimientos
Manual de procedimientosManual de procedimientos
Manual de procedimientos
 
6 Referral Marketing Best Practices To Turn Customers Into Word-Of-Mouth Mark...
6 Referral Marketing Best Practices To Turn Customers Into Word-Of-Mouth Mark...6 Referral Marketing Best Practices To Turn Customers Into Word-Of-Mouth Mark...
6 Referral Marketing Best Practices To Turn Customers Into Word-Of-Mouth Mark...
 
Qué es filosofía
Qué es filosofíaQué es filosofía
Qué es filosofía
 
Cloud-powered Continuous Integration and Deployment architectures - Jinesh Varia
Cloud-powered Continuous Integration and Deployment architectures - Jinesh VariaCloud-powered Continuous Integration and Deployment architectures - Jinesh Varia
Cloud-powered Continuous Integration and Deployment architectures - Jinesh Varia
 

More from Marc Bächinger

Introduction to web components
Introduction to web componentsIntroduction to web components
Introduction to web componentsMarc Bächinger
 
Modern web application network architecture
Modern web application network architectureModern web application network architecture
Modern web application network architectureMarc Bächinger
 
Architecting non-trivial browser applications (Jazoon 2012)
Architecting non-trivial browser applications (Jazoon 2012)Architecting non-trivial browser applications (Jazoon 2012)
Architecting non-trivial browser applications (Jazoon 2012)Marc Bächinger
 

More from Marc Bächinger (9)

Introduction to web components
Introduction to web componentsIntroduction to web components
Introduction to web components
 
High-Quality JavaScript
High-Quality JavaScriptHigh-Quality JavaScript
High-Quality JavaScript
 
HTML5 unplugged
HTML5 unpluggedHTML5 unplugged
HTML5 unplugged
 
Modern web application network architecture
Modern web application network architectureModern web application network architecture
Modern web application network architecture
 
JavaScript toolchain
JavaScript toolchainJavaScript toolchain
JavaScript toolchain
 
With your bare hands
With your bare handsWith your bare hands
With your bare hands
 
Architecting non-trivial browser applications (Jazoon 2012)
Architecting non-trivial browser applications (Jazoon 2012)Architecting non-trivial browser applications (Jazoon 2012)
Architecting non-trivial browser applications (Jazoon 2012)
 
Jax-rs-js Tutorial
Jax-rs-js TutorialJax-rs-js Tutorial
Jax-rs-js Tutorial
 
Html5 communication
Html5 communicationHtml5 communication
Html5 communication
 

JQuery primer

  • 2. PRIMARY USE CASE Dienstag, 11. Februar 14
  • 3. BROWSER FACADE App code Dienstag, 11. Februar 14 use jQuery use Browser API Browser API Browser API Browser API
  • 4. BROWSER FACADE • smooth out browser incompatibilities • shield from verbose W3C DOM API • countless utilities for convenient development Dienstag, 11. Februar 14
  • 5. JQUERY IS A LIBRARY • ultimate productivity boost • no application lifecycle provided • no MVC infrastructure provided • no component model (jQuery UI has) • lacks a decent object oriented approach • easy to create code which is hard to maintain • jQuery code sprinkled all over markup Dienstag, 11. Februar 14
  • 6. jQuery - core browser facade jQuery UI - User Interface components jQuery mobile - mobile UI framework QUnit - unit/component testing framework Sizzle - CSS selector engine Dienstag, 11. Februar 14
  • 7. 101: PROBLEM SPACES • selecting DOM elements • traversing the DOM • manipulating DOM elements • setting CSS properties • handling browser events • browser networking Dienstag, 11. Februar 14
  • 9. 101: BASIC WORKFLOW 1. select (query) elements 2. operate on selection Dienstag, 11. Februar 14
  • 10. 101: SELECTORS support for CSS3 selectors and more // select an element by id $("#menu").addClass("menu-theme-dark"); // select elements by class $(".menu-item").removeClass("active"); // select elements by tag name $("body").removeClass("small-screen"); // a list items with a give class in a given anchestor $("#menu li.active").removeClass("active"); // all elements with a given attr in a given anchestor $("#menu [data-action]").css("border-top", "1px solid red"); Dienstag, 11. Februar 14
  • 11. 101: SELECTORS #menu .item <ul id=“menu“> <li class=“item“></li> <li class=“item“></li> </ul> .item:first-child <ul id=“menu“> <li class=“item“></li> <li class=“item“></li> </ul> .item.selected <ul id=“menu“> <li class=“item selected“></li> <li class=“item“></li> </ul> [data-action] <button data-action=“edit“>edit</button> <i data-action=“del“>delete</i> Dienstag, 11. Februar 14
  • 12. 101: SELECTORS #menu li #menu > li Dienstag, 11. Februar 14 <ul id=“menu“> <li class=“item“> <ul> <li></li> </ul> </li> </ul> <ul id=“menu“> <li class=“item“> <ul> <li></li> </ul> </li> </ul>
  • 13. 101: SELECTORS #menu li, .list li <ul id=“menu“> <li class=“item“></li> </ul> <ul class=“list“> <li></li> </ul> tr:hover td Dienstag, 11. Februar 14 <tr> <td></td> <td></td> <td></td> </tr>
  • 14. 101: FLUID API fluid API style allows to chain operations on a given selection $(".menu-item") .removeClass("active") .addClass("inactive ") .css("padding-left", "0px") .find(".trigger") .click(function(ev) { ... }) .each(function () { ... }); Dienstag, 11. Februar 14
  • 15. 101: FLUID API fluid API style allows to chain operations on a given selection $(".menu-item") .removeClass("active") .addClass("inactive ") .css("padding-left", "0px") .find(".trigger") .click(function(ev) { // spaghetti carbonara? }) .each(function () { // spaghetti napoli? }); Dienstag, 11. Februar 14
  • 17. 101: EVENTS trigger.on("mouseover", function (ev) { // fired on mouse over the trigger }); trigger.click(function (ev) { // short-cut for common events }); sidebar.on("click", ".menu a", function () { // handle all menu items with a single handler }); sidebar.on("click", "tr td:first-child", function () { // handle all clicks on the first cell of any row }); Dienstag, 11. Februar 14
  • 18. 101: CATCHING BUBBLING EVENTS Hans Vreni Karl Meier Huber Wehrli 1967 1982 1912 m w m e e e - <button data-action=“remove-row“>-</button> $("#data-table").click(function(ev) { }); Dienstag, 11. Februar 14 var action = $(ev.target).data("action"); if (action === "remove-row") { var personId = $(ev.target).closest(„[data-id]“]; ... } else if (action === "edit-row") { ... }
  • 19. 101: CUSTOM EVENTS // jQuery lets you trigger events $("#btn").trigger("click"); Dienstag, 11. Februar 14
  • 20. 101: CUSTOM EVENTS // jQuery lets you trigger events $("#btn").trigger("click"); // custom events are allowed; so... container.on("msg:myApp", function (ev, data) { // update UI }); Dienstag, 11. Februar 14
  • 21. 101: CUSTOM EVENTS // jQuery lets you trigger events $("#btn").trigger("click"); // custom events are allowed; so... container.on("msg:myApp", function (ev, data) { // update UI }); btn.click(function (ev) { btn.trigger("msg:myApp", { name: "age", val: 42, type: "update" }); }); Dienstag, 11. Februar 14
  • 23. 101: AJAX $.ajax({ url: "/api/order", type: "PUT" data: { userId: 1234, lineItems: lineItems}, dataType: "json" success: function (data) { emitEvent("sent-order", data); }, error: function (jqXhr) { growl("sending order failed"); } }); Dienstag, 11. Februar 14 +
  • 24. 101: AJAX CONVENIENCE // simplified GET requests $.get("/dashboard", function (htmlOrXmlResponse) { alert(htmlOrXmlResponse); }); // POST form data $.post("/contact", $("#contact-form").serialize(), function () { alert("success"); } ); // json reponse parsed to js object $.getJSON("/persons.", function (data) { alert(data); }); // load content of url into an element $("#content").load("partials/dashboard.html"); Dienstag, 11. Februar 14
  • 25. 101: GLOBAL AJAX var pendingCount = 0; $(document).ajaxStart(function() { if (pendingCount === 0) { $( "#spinner" ).show(); } pendingCount++; }); $(document).ajaxComplete(function() { pendingCount--; if (pendingCount === 0) { $( "#spinner" ).hide(); } }); Dienstag, 11. Februar 14
  • 26. 101: GLOBAL AJAX /** * ajaxPrefilter is called for each request processed * with $.ajax or other jQuery http functions */ $.ajaxPrefilter(function(options, origOptions, jqXHR) { // set the Authorization header for all request options.headers = { Authorization: "Basic " + btoa("chopen2013:chopen2013") }; }); Dienstag, 11. Februar 14
  • 28. 101: CONVENIENCE // setting removing style classes $(".item").addClass("myClass"); $(".item").removeClass("myClass"); $(".item").toggleClass("myClass"); // display, hide selected elements $("#item").show(); $("#item").hide(); $("#item").toggle(); $("#item").fadeIn(); $("#item").fadeOut(); Dienstag, 11. Februar 14
  • 29. 101: EACH compared to for-loops ,each‘ is slower, but safer $.each([1,2,3,4,5], function (idx, item) { trigger.on(„click“, function() { // use idx and item here with no worries }; }); var person = { firstName: "Helge", lastName: "Schneider" }; $.each(person, function (key, value) { // ... // value is bound to this }); Dienstag, 11. Februar 14