JQuery primer

31
Dienstag, 11. Februar 14

description

jQuery primer for the workshop "JavaScript for the enterprise" held at the /ch/open-Workshop Tage 2013.

Transcript of JQuery primer

Dienstag, 11. Februar 14

PRIMARY USE CASE

Dienstag, 11. Februar 14

BROWSER FACADE

jQuery

Browser API

App codeuse use Browser API

Browser APIBrowser API

Dienstag, 11. Februar 14

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 facadejQuery UI - User Interface componentsjQuery mobile - mobile UI frameworkQUnit - unit/component testing frameworkSizzle - 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

// 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");

support for CSS3 selectors and more

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 <ul id=“menu“> <li class=“item“> <ul> <li></li> </ul> </li> </ul>

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

Dienstag, 11. Februar 14

101: SELECTORS

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

<ul class=“list“> <li></li> </ul>

tr:hover td <tr> <td></td> <td></td> <td></td> </tr>

Dienstag, 11. Februar 14

101: FLUID API

$(".menu-item").removeClass("active").addClass("inactive ").css("padding-left", "0px").find(".trigger").click(function(ev) { ...}).each(function () { ...});

fluid API style allows to chain operations on a given selection

Dienstag, 11. Februar 14

101: FLUID API

$(".menu-item").removeClass("active").addClass("inactive ").css("padding-left", "0px").find(".trigger").click(function(ev) { // spaghetti carbonara?}).each(function () { // spaghetti napoli?});

fluid API style allows to chain operations on a given selection

Dienstag, 11. Februar 14

EVENTS

Dienstag, 11. Februar 14

101: EVENTStrigger.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

<button data-action=“remove-row“>-</button>

$("#data-table").click(function(ev) {

var action = $(ev.target).data("action"); if (action === "remove-row") { var personId = $(ev.target).closest(„[data-id]“]; ...

} else if (action === "edit-row") { ... } });

Hans Meier 1967 mVreni Huber 1982 wKarl Wehrli 1912 m

e

e

e -

-

-

Dienstag, 11. Februar 14

101: CUSTOM EVENTS// jQuery lets you trigger events$("#btn").trigger("click");

Dienstag, 11. Februar 14

101: CUSTOM EVENTS

// custom events are allowed; so...container.on("msg:myApp", function (ev, data) { // update UI});

// jQuery lets you trigger events$("#btn").trigger("click");

Dienstag, 11. Februar 14

101: CUSTOM EVENTS

// custom events are allowed; so...container.on("msg:myApp", function (ev, data) { // update UI});

// jQuery lets you trigger events$("#btn").trigger("click");

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

$.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

});

compared to for-loops ,each‘ is slower, but safer

Dienstag, 11. Februar 14

LUNCH!Dienstag, 11. Februar 14

EXERCISES

~/ws/03-jQuery/exercises

Dienstag, 11. Februar 14