52
jQuery Makes Writing JavaScript Fun Again Doris Chen Ph.D. Developer Evangelist Microsoft http://blogs.msdn.com/b/dorischen/

jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Embed Size (px)

DESCRIPTION

Get frustrated by cross-browser incompatibility? Hate to develop application using JavaScript? jQuery is a powerful JavaScript library that can enhance your websites regardless of your background. jQuery is fast, lean, simple and hugely expandable, enabling you to build compelling web applications quickly and easily. In this session, we will start with a quick introduction of jQuery, illustrate what’s so good about jQuery, and demonstrate step by step how to develop jQuery Ajax application efficiently with database, web services, OData, NetFlix and ASP.NET MVC. Microsoft is now shipping, supporting, and contributing to jQuery, with ASP.NET and Visual Studio. New features which will be available in the next release of jQuery such as globalization, templating and data-linking will be introduced in the session as well.

Citation preview

Page 1: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

jQuery Makes Writing JavaScript

Fun Again

Doris Chen Ph.D. Developer Evangelist

Microsoft

http://blogs.msdn.com/b/dorischen/

Page 2: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Who am I?

• Developer Evangelist at Microsoft based in Silicon Valley, CA

– Blog: http://blogs.msdn.com/b/dorischen/

– Twitter @doristchen

– Email: [email protected]

• Has over 13 years of experience in the software industry focusing on

web technologies

• Spoke and published widely at JavaOne, O'Reilly, SD West, SD

Forum and worldwide User Groups meetings

• Before joining Microsoft, Doris Chen was a Technology Evangelist at

Sun Microsystems

• Doris received her Ph.D. from the University of California at Los

Angeles (UCLA)

Page 3: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Agenda

• Essentials of jQuery

• New jQuery Plugins: Templates, DataLink, Globalization

• Working with OData, JSONP, Netflix

• Working with Web Services, Database and OData

• Summary

Page 4: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

What is AJAX?

• Ajax= acronym for: > Asynchronous JavaScript And XML(or

XMLHTTPRequest )

• Browser client uses JavaScript to Asynchronously get data from a server and update page dynamically without refreshing the whole page

• More interactive user experience

Page 5: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

“Naked” Ajax is too complex

• A lot of JavaScript programming involved > “It is buggy and broken”

> “Used for annoying people”

> Difficult to debug and maintain

> ...

• You need a deep understanding of Ajax techniques

• Have to handle all XmlHttpRequest interactions yourself

• Have to handle cross browser inconsistence yourself

Page 6: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Solutions • JavaScript Toolkits

> Wrap up ajax details in javascript libraries

> jQuery, Dojo, prototype+scriptaculous, Yahoo,...

Page 7: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

jQuery Adoption

http://trends.builtwith.com/javascript/JQuery

Page 8: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

What is jQuery?

• Created by John Resig and first announced Jan 2006 at BarCampNYC

• Most popular JavaScript library in use today > simplifies the interaction between HTML and JavaScript

• Free, open source (MIT, GPL)

• Cross Browser > IE6+, FF2+, Sarari 3+, Chrome, Opera 9+

• Find it at http://jquery.com

• It’s a joy to use

Page 9: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Why jQuery ? • Cross-browser compatibility • Fast & Small

– 24KB in size (Minified and Gzipped) – Core is minimum and add Plugins when

• Short Learning curve & Great Documentation • Tons of Plug-in: jQuery plugin repository • CSS3 Selectors Compliant • Helpful Utilities

– string trimming, easily extend objects, iteration, array manipulation, support function

• jQuery UI: jQuery User Interface • Widespread Adoption

– Google, Microsoft, Amazon, Twitter, Dell, Mozilla, Wordpress & Drupal, HP, IBM, Intel, Ruby on Rails

Page 10: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Getting Start

• Download jQuery at jquery.com – <script type="text/javascript" src="/js/jQuery. js"></script>

• Microsoft CDN or Google CDN – <script src="http://ajax.microsoft.com/ajax/jquery/jquery-

1.4.2.js" type="text/javascript"></script>

– <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>

Page 11: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

jQuery Philosophy

Find someone from HTML (selector)

Do something to it

(method)

Page 12: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Focus of jQuery

• Find someone in HTML and do something

$(“div”).addClass(“header”)

• JQuery object > Commonly used “$”

> Can also named “jQuery”

jQuery(“div”).addClass(“header”)

Page 13: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Find Someone: Selector • CSS Style

– $(“#myID”) // by id – $(“.myClass”) // by class name – $(“myTag”) // by tag (element name) – $(“#id, .class, tag”) // multiple

• Hierarchy – $("form input") // descendant – $("#main > *") // child – $("#prev ~ div") // sibling

• Form – $("form :radio") – $("#dvMainForm :checkbox") – $("input:disabled")

Page 14: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Do something with the found

elements

• Attributes get/set

• Manipulation

• Events

• Effects

• AJAX

Page 15: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Attribute

• $("em").attr("title")

• $("label").html()

• $("p:first").text()

• $("input").val() • $("em").attr("title", "zupzip")

• $("label").html("zupzip")

• $("p:first").text("zupzip")

• $("input").val("zupzip")

Get

Set

Page 16: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Manipulation

• Apply css style dynamically – $(“#target”).addClass(“css_class”);

• Toggle css style – $(“#target”).toggleClass(“css_class”);

• Append – $("p").append("<strong>Hello</strong>");

• appendTo – $("span").appendTo("#foo");

• prepend &prependTo • after

– $("p").after("<b>Hello</b>"); • before

– $("p").before("<b>Hello</b>"); Manipulations Demo

Page 17: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Events

• click, hover, change....

$(“#target”).click(function(){....});

• bind

$(“#target”).bind(“click”, function(){....});

• Chain event handlers

$(“#target”).click(....).hover(...);

Events Demo

Page 18: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Effects

• Show and Hide

– $(“#target”).show()

– $(“#target”).hide()

• Fade in and out

– $(“#target”).fadein()

– $(“#target”).fadeout()

• Slide up and down

– $(“#target”).slideup()

– $(“#target”).slidedown()

• Custom animation Animation Demo

Page 19: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

AJAX • load(url, [data], callback)

> $(„#myContainer‟).load(„home/myHtmlSnippet‟);

• $.get(url, [data], callback)

• $.post(url, [data], callback)

• $.ajax(options) > $.ajax({ type : “GET” url : “url” data : data success : callback });

Page 20: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

jQuery Stack & Chaining

$(‘body’) // [body]

.find(‘p’) // [p, p, p] > [body]

.find(‘a’) // [a, a] > [p, p, p] > [body]

.addClass(‘foo’)

.end() // [p, p, p] > [body]

.end() // [body]

20

Page 21: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

jQuery Stack & Chaining

$(‘tr’) //get all rows

.filter(‘:odd’) //get all odd rows

.addClass(‘myOddClass’)

.end() //back to all rows

.filter(‘:even’) //get all even rows

.addClass(‘myEvenClass’);

21

Page 22: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Agenda

• Essentials of jQuery

• New jQuery Plugins: Templates, DataLink, Globalization

• Working with OData, JSONP, Netflix

• Working with Web Services, Database and OData

• Summary

Page 23: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Microsoft is Contributing to jQuery Library

• jQuery Templates plugin, Data Link plugin, and Globalization plugin have been accepted as officially supported plugins of the jQuery project

– jQuery Templates (with jQuery 1.4.2) and Datalink plugins (with jQuery 1.4.3) will be managed by the jQuery Core team

– jQuery Globalization plugin will become part of the jQuery UI project

– jQuery Templates plugin will be part of jQuery Core library 1.5

• API Documentation

– jQuery Templates http://api.jquery.com/category/plugins/templates/

– jQuery Data Link– http://api.jquery.com/category/plugins/data-link/

– jQuery Globalization– Available soon

• Download

– jQuery Templates – http://github.com/jquery/jquery-tmpl

– jQuery Datalink – http://github.com/jquery/jquery-datalink

– jQuery Globalization – http://github.com/jquery/jquery-global

• Full product support for jQuery

– Ship with Visual Studio with Great Intellisense support

Page 24: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Templates Plugin (jQuery 1.4.2) • create client templates

– e.g. format a set of database records from the server through an Ajax request

<body> <ul id="movieList"></ul> <script id="movieTemplate" type="text/x-jquery-tmpl"> <li><b>${Name}</b> (${ReleaseYear})</li> </script> <script src="http://code.jquery.com/jquery-latest.min.js"></script> <script src="http://nje.github.com/jquery-tmpl/jquery.tmpl.js"></script>

<script> var movies = [ { Name: "The Red Violin", ReleaseYear: "1998" }, { Name: "Eyes Wide Shut", ReleaseYear: "1999" }, { Name: "The Inheritance", ReleaseYear: "1976" } ]; $( "#movieTemplate" ).tmpl( movies ) .appendTo( "#movieList" ); </script> </body>

Page 25: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Datalink Plugin (jQuery 1.4.3) • Easily keep user interface and data synchronized

– automatically synchronize the input fields of a form with the properties of JavaScript product object

<script src="http://github.com/nje/jquery-datalink/raw/e3e3be4312c9b224a8d9b25031f4ac876e4f70fd/jquery.js"></script> <script src="http://github.com/nje/jquery-datalink/raw/master/jQuery.datalink.js"></script>

<form> <div> First Name: <input type="text" name="firstName" /> </div></form>

person.firstName: <span id="objFirst"></span><br/> <script> var person = {}; $("form").link(person); // Chain link the person object to these elements to show the results $("#objFirst").link(person, { firstName: { name: "objFirst", convertBack: function (value, source, target) { $(target).text(value); } } }); $(person).data("firstName", "John"); </script>

Page 26: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Globalization Plugin (jQuery 1.4.2)

• enables you to use different cultural conventions

• formatting or parsing numbers, dates and times, calendars, and currencies

• has information on over 350 cultures

• can use this plugin with the core jQuery library or plugins built on top of the jQuery library

Page 27: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Agenda

• Essentials of jQuery

• New jQuery Plugins: Templates, DataLink, Globalization

• Working with OData, JSONP, Netflix

• Working with Web Services, Database and OData

• Summary

Page 28: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Develop Netflix Movie Search Application using

jQuery, OData, JSONP and Netflix Technologies

OData Query

OData in JSON

http://odata.netflix.com/Catalog/Titles?$filter=Name%20eq%20'Star%20Trek'

Netflix OData Provider

JSONP Ajax Call

Callback Render on jQuery Template

Page 29: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

OData

• Web protocol for querying and updating data • Uniform way of representing structured data

– Atom, JSON formats

• Uniform URL conventions – Navigation, filtering, sorting, paging, etc.

• /Bookmarks?$orderby=Name //sorting • /Bookmarks?$top=10&$skip=30 //paging

• Uniform operations – Addressability – GET, POST, PUT, DELETE

• http://www.odata.org/

Page 30: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Netflix OData in Atom

Page 31: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Netflix OData in Feeder Reading View

Page 32: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Netflix OData Diagram

http://odata.netflix.com/Catalog/Titles?$filter=Name%20eq%20'Star%20Trek'

Query String

Page 33: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Key Steps

• Start with an empty HTML page • Define style or you can put it in a css file • Develop start up page • Define the template of the response page • Compose the JSONP call • Implement callback routine and using jQuery template

– Microsoft has contributed jQuery template jquery.tmpl.js to jQuery project and it will be part jQuery in next release.

• Implement movie play using Netflix API – You need to apply a Netflix Developer API account and get the

key. – More information http://developer.netflix.com/

Page 34: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Style

<head> <title>Search Movies</title> <style type="text/css"> #movieTemplateContainer div { width:400px; padding: 10px; margin: 10px; border: black solid 1px; } </style> </head>

Page 35: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Start Up Page and Template Result Page

<body> <label>Search Movies:</label> <input id="movieName" size="50" /> <button id="btnLookup">Lookup</button> <div id="movieTemplateContainer"></div> <script id="movieTemplate" type="text/x-jquery-tmpl"> <div> <img src="${BoxArt.LargeUrl}" /> <strong>${Name}</strong> <br/> <button id="playButton" movieID=${NetflixApiId}

onclick="play(this)">Play Now</button> <p> {{html Synopsis}} </p> </div> </script>

<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="Scripts/jquery.tmpl.js"></script>

Page 36: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Make JSONP Call <script type="text/javascript"> $("#btnLookup").click(function () { // Build OData query var movieName = $("#movieName").val(); var query = "http://odata.netflix.com/Catalog" // netflix base url + "/Titles" // top-level resource + "?$filter=substringof('" + escape(movieName) + "',Name)" //filter by movie name + "&$callback=callback" // jsonp request + "&$format=json"; // json request // Make JSONP call to Netflix $.ajax({ dataType: "jsonp", url: query, jsonpCallback: "callback", success: callback }); });

Page 37: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Callback and Template

<div id="movieTemplateContainer"></div> <script id="movieTemplate" type=" text/x-jquery-tmpl "> <div> <img src="${BoxArt.LargeUrl}" /> <strong>${Name}</strong> <br/> <button id="playButton" movieID=${NetflixApiId} onclick="play(this)">Play Now</button>

<p> {{html Synopsis}} </p> </div> </script>

function callback(result) {

// unwrap result var movies = result.d.results; $("#movieTemplateContainer")

.empty(); $("#movieTemplate").tmpl(movies).appendTo("#movieTemplateContainer"); }

Page 38: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Netflix Movie Play function play(mvInfo) { var id = $(mvInfo).attr("movieID").substring(45); javascript: nflx.openPlayer('http://api.netflix.com/catalog/movie/'+id, 0, 0, ‘YOUR NETFLIX DEVELOPER ACCOUNT KEY'); } </script> <script src="http://jsapi.netflix.com/us/api/js/api.js"></script>

</body>

Page 39: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)
Page 40: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Agenda

• Essentials of jQuery

• New jQuery Plugins: Templates, DataLink, Globalization

• Working with OData, JSONP, Netflix

• Working with Web Services, Database and OData

• Summary

Page 41: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Developing jQuery Application

• Server Agnostic • Server

– Data Model: entity framework, JPA, etc – Develop Restful Web Services (OData Services)

• Client – Invoke Restful Web Services (OData Services) $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "/MovieService.svc/Movies", data: data, dataType: "json", success: insertCallback }); – Retrieve data and Present

• JavaScript, jQuery, jQuery templates, jQuery plugins, HTML5

Page 42: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Favorite Movie Site Overview

Insert Data into Database

Displaying Movie List

Page 43: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Key Steps: Insert Data into Database

• Create ADO.NET Entity Data Model based on the

DB • Approach 1: Using generic handler

– low-level approach to interacting with .NET through jQuery

– Simple, just need jQuery library

• Approach 2: Using Ajax-enabled WCF Service – a little more work as need to serialize objects into JSON

• Approach 3 Using OData (WFC Data Service) – Taking advantage of open standards such as REST, JSON,

and OData – The OData protocol (WCF Data Services) works very

nicely with Ajax • quickly expose database data to an Ajax application

Page 44: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Create a Data Model

Page 45: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Approach 3: Create OData Service

Page 46: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Approach 3: Insert Data Using OData Service

Create WCF Data Service (OData Service) public class MovieService : DataService<MoviesEntities> {// This method is called only once to initialize service-wide policies. public static void InitializeService(DataServiceConfiguration config) {// TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc. // Examples: config.SetEntitySetAccessRule("Movies", EntitySetRights.All); // config.SetServiceOperationAccessRule("MyServiceOperation", ServiceOperationRights.All); config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2; } }

AddMovie.aspx $("#btnAdd").click(function () { // Convert the form into an object var data1 = { Title: $("#title1").val(), Genre: $("#genre").val(), ImageURL: $("#imageUrl").val() }; // JSONify the data var data = JSON.stringify(data1); // Post it $.ajax({ type: "POST", contentType: "application/json; charset=utf-8", url: "/MovieService.svc/Movies", data: data, dataType: "json", success: insertCallback }); }); function insertCallback(result) { var newMovie = result["d"]; // Show primary key alert("Movie added with primary key " + newMovie.MovieID); }

Page 47: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Display Favorite Movies • Retrieving movie list from OData

– Approach 1: using jQuery and jQuery Plugin templates to create a table with pagination

– Approach 2: using jQuery, jQuery Plugin templates and Element Stack Plugin to create a fun Movie list

• http://www.marcofucci.com/tumblelog/15/mar/2010/elementstack_v1-1/

Page 48: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Agenda

• Essentials of jQuery

• New jQuery Plugins: Templates, DataLink, Globalization

• Working with OData, JSONP, Netflix

• Working with Web Services, Database and OData

• Summary

Page 49: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Summary

• jQuery is easy to learn and use

– jQuery plugins, jQuery UI

• Microsoft is contributing to jQuery project

• jQuery can work with different server platform

– Easy to produce and consume Restful Web Services, OData

Page 50: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Resources • jquery.com Downloading

• api.jquery.com Documentation

• forum.jquery.com Community

• meetups.jquery.com Local Community

• plugins.jquery.com Extending

• jqueryui.com UI Widgets and Effects

• odata.org OData Services

Page 51: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

Upcoming Web Camps 1 Day MVC and jQuery Web Camp

Feb. 26th, 2011, Mountain View, CA

March 25th, 2011, Seattle, WA

Free, learning innovative web technology, hands on experience

Detail and Registration http://bit.ly/gT9sBb

Page 52: jQuery Makes Writing JavaScript Fun Again (for HTML5 User Group)

jQuery Makes Writing JavaScript

Fun Again

Doris Chen Ph.D.

[email protected] Developer Evangelist

Microsoft

http://blogs.msdn.com/b/dorischen/