Your SlideShare is downloading. ×
What's new in jQuery 1.5
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Introducing the official SlideShare app

Stunning, full-screen experience for iPhone and Android

Text the download link to your phone

Standard text messaging rates apply

What's new in jQuery 1.5

3,830
views

Published on

A quick introduction to jQuery 1.5 by Martin Kleppe. He gave this talk at the Hamburg JavaScript User Group @hhjs.

A quick introduction to jQuery 1.5 by Martin Kleppe. He gave this talk at the Hamburg JavaScript User Group @hhjs.

Published in: Technology

1 Comment
4 Likes
Statistics
Notes
No Downloads
Views
Total Views
3,830
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
32
Comments
1
Likes
4
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. jQuery 1.5Martin Kleppe @aemkeiMartin Kleppe @aemkeihttp://ubilabs.nethttp://ubilabs.net
  • 2. Whats new Ajax rewrite Ajax rewrite Deferred Objects Deferred Objects performance improvements performance improvements new methods new methods
  • 3. Stats 207 kb regular 207 kb regular 29 kb minified gzip 29 kb minified gzip 83 fixed bugs 83 fixed bugs 460 closed tickets 460 closed tickets
  • 4. CDNhttp://ajax.googleapis.com/http://ajax.googleapis.com/ajax/libs/jquery/1 ..5 ..0 //ajax/libs/jquery/1 5 0jquery.min.jsjquery.min.js
  • 5. CDN Minor Version http://ajax.googleapis.com/ http://ajax.googleapis.com/ ajax/libs/jquery/1 ..5 // ajax/libs/jquery/1 5 jquery.min.js jquery.min.js
  • 6. Traversal Performance .children() ,, .prev() ,, .next() .children() .prev() .next() substantial speed-ups substantial speed-ups
  • 7. Build System Java/Rhino ! V8/NodeJS Java/Rhino ! V8/NodeJS Google Closure Compiler ! UglifyJS Google Closure Compiler ! UglifyJS
  • 8. New Methods $.parseXML() $.parseXML() Parses string into XML Parses string into XML .clone( true, true ) .clone( true, true ) Clone deep with data and events Clone deep with data and events
  • 9. Ajax Rewrite complete rewrite complete rewrite consistency across the API consistency across the API
  • 10. Affected MethodsjQuery.ajax() // asynchronous HTTP requestjQuery.get() // load data using GETjQuery.getJSON() // load JSON-encoded datajQuery.getScript() // load JS filejQuery.post() // load data using POST
  • 11. Old School$.ajax({ url: "/example" }, { success: function(){ // horray! }});
  • 12. New School$.ajax({ url: "/example" }). success( function(){ /* horray! */} );
  • 13. New School$.ajax({ url: "/example" }). success( function(){ /* horray! */} );
  • 14. Chaining Handlersvar jqxhr = $.ajax({ url: "/example" }) .success( /* success handler */ ) .error( /* error handler */ ) .complete( /* 1st complete handler */ );
  • 15. Further Handlersvar jqxhr = $.ajax({ url: "/example" }) .success( /* success handler */ )// perform other work here ...jqxhr.success( /* 2nd success handler */ )
  • 16. Abort Ajaxvar jqxhr = $.ajax({ url: "/example" }) .success( /* success handler */ );setTimeout(function(){ jqxhr.abort();}, 1000);
  • 17. Extensible P r e f i l t e r s - beforeSend callbacks P r e f i l t e r s - beforeSend callbacks C o n v e r t e r s - dataFilter callbacks C o n v e r t e r s - dataFilter callbacks T ra n s p o r t s - used internally T ra n s p o r t s - used internally
  • 18. Prefilters called before each request is sent called before each request is sent prior to any $.ajax() option handling prior to any $.ajax() option handling
  • 19. $.ajaxPrefilter()$.ajaxPrefilter( function( options, originalOptions, jqXHR ) { // your code here });// originalOptions: options provided to method// unmodified + without defaults from ajaxSettings
  • 20. Handle Custom Optionsvar currentRequests = {};// abort duplicated request$.ajaxPrefilter( function( options, originalOptions, jqXHR ) { if ( options.abortOnRetry ) { if ( currentRequests[ options.url ] ) { currentRequests[ options.url ].abort(); } currentRequests[ options.url ] = jqXHR; } });
  • 21. Modify Existing Options// cross-domain proxy$.ajaxPrefilter( function( options ) { if ( options.crossDomain ) { var url = e n c o d e U R I C o m p o n e n t ( options.url ); options.url = "/proxy?url=" + url; options.crossDomain = false; }});
  • 22. Prefilter dataType// prefilter to JSON and script requests$.ajaxPrefilter( "json script", function() { // ...});
  • 23. Modify Target dataType// set a request as "script"$.ajaxPrefilter(function( options ) { if ( isActuallyScript( options.url ) ) { return "script"; }});// all prefilters attached to "script" dataType// would be applied to it
  • 24. Converters handle response of certain dataType handle response of certain dataType while another dataType is expected while another dataType is expected stored into ajaxSettings stored into ajaxSettings can be added globally can be added globally
  • 25. Global converters$.ajaxSetup({ converters: { "text mydatatype": function( textValue ) { if ( valid( textValue ) ) { // some parsing logic here return mydatatypeValue; } else { // notify a parsererror throw exceptionObject; } } }});
  • 26. Converters useful to introduce custom dataTypes useful to introduce custom dataTypes can be used to transform data into desired formats can be used to transform data into desired formats Note: custom dataTypes must be lowercase Note: custom dataTypes must be lowercase
  • 27. Request Data of Type "mydatatype"$.ajax( url, { dataType: "mydatatype"});
  • 28. "Inline" Converters// requests XML document$.ajax( url, { dataType: "xml text mydatatype", converters: { "xml text": function( xmlValue ) { // extract relevant text from XML // parses it as "mydatatype" return textValue; } }});
  • 29. Handling Custom Data Types Standard dataTypes: "text", "json", "xml", "html" Standard dataTypes: "text", "json", "xml", "html" Use converters option in $.ajaxSetup() Use converters option in $.ajaxSetup() to modify data type conversion strategies to modify data type conversion strategies
  • 30. Data Converters in jQuery Source// format: "source_type destination_type"// "*" can be used for source_typeconverters: { // Convert anything to text "* text": window.S t r i n g , // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML}
  • 31. Transports most advanced way to enhance $.ajax() most advanced way to enhance $.ajax() used internally by $.ajax() to issue requests used internally by $.ajax() to issue requests should be used only as a last resort should be used only as a last resort when prefilters and converters are insufficient when prefilters and converters are insufficient object with two methods: send and abort object with two methods: send and abort
  • 32. Transports each request requires its own instance each request requires its own instance tranports cannot be registered directly tranports cannot be registered directly registered using $.ajaxTransport() registered using $.ajaxTransport() provide a function that returns transport instead provide a function that returns transport instead
  • 33. Transports factories$.ajaxTransport( function( options, originalOptions, jqXHR ) { return { send: function( headers, completeCallback ) { // headers: map of request headers // completeCallback: notify of completion }, abort: function() { /* abort code */ } }; });
  • 34. Option: completeCallback// completeCallback signaturefunction( status, // HTTP status code statusText, // status text of response [responses], // map of dataType/value [headers] // response headers)
  • 35. Attach to Specific dataType// can be attached to specific dataType// just like prefilters$.ajaxTransport( "script", function( options, originalOptions, jqXHR ) { /* only be called for script requests */ });
  • 36. jQuery.Deferred work with return values that may not be work with return values that may not be immediately present immediately present chainable utility object chainable utility object register multiple callbacks (callback queues) register multiple callbacks (callback queues) relay on success or failure state relay on success or failure state
  • 37. Assign Handlers// remember request objectvar jqxhr = $.ajax({ url: "/example" }) .success( /* success handler */ ) .error( /* error handler */ ) .complete( /* 1st complete handler */ );// perform other work here ...jqxhr.complete( /* 2nd complete handler */ );
  • 38. jQuery.Deferred then() ,, done() ,, fail - functions to be called then() done() fail - functions to be called resolve ,, reject - “call” them with your arguments resolve reject - “call” them with your arguments state stays once it has been resolved state stays once it has been resolved eg: second call to resolve is ignored eg: second call to resolve is ignored functions added later are called immediately functions added later are called immediately
  • 39. jQuery.Deferred Constructor[new] jQuery.Deferred( [method] )// optional new keyword// method called before constructor returns
  • 40. jQuery.Deferred Constructorfunction(){ var deferred = new jQuery.Deferred(); // asnyc code return deferred.promise();}
  • 41. jQuery.Deferred Example$.wait = function(time) { var deferred = new jQuery.Deferred(); setTimeout(deferred.resolve, time); return deferred.promise();}
  • 42. jQuery.Deferred Shorthand return $.Deferred(function( deferred ) { // your async code }).promise();  
  • 43. jQuery.Deferred Shorthand$.wait = function(time) { return $.Deferred(function( deferred ) { setTimeout(deferred.resolve, time); }).promise();};
  • 44. Deferred Live Cycle starts in the u n r e s o l v e d state starts in the u n r e s o l v e d state callbacks are queued to be executed later callbacks are queued to be executed later resolve transitions into r e s o l v e d state resolve transitions into r e s o l v e d state immediately executes any doneCallbacks immediately executes any doneCallbacks reject transitions into r e j e c t e d state reject transitions into r e j e c t e d state immediately executes any failCallbacks immediately executes any failCallbacks after transitions, it stays in that state after transitions, it stays in that state callbacks now execute immediately callbacks now execute immediately
  • 45. Deferred Objects Methods .done() - called when state is resolved .done() - called when state is resolved .fail() - called when state is rejected .fail() - called when state is rejected .then() - called when state is resolved or rejected .then() - called when state is resolved or rejected .isRejected() - determine rejected state .isRejected() - determine rejected state .isResolved() - determine resolved state .isResolved() - determine resolved state
  • 46. Deferred Objects Methods .reject() - reject and call failCallbacks .reject() - reject and call failCallbacks .rejectWith() - reject with context .rejectWith() - reject with context .resolve() - resolve and call doneCallbacks .resolve() - resolve and call doneCallbacks .resolveWith() - resolve with context .resolveWith() - resolve with context
  • 47. jQuery.when() execute callback functions execute callback functions based on one or more objects based on one or more objects usually Deferred objects usually Deferred objects (represent asynchronous events) (represent asynchronous events)
  • 48. jQuery.when()function doAjax(){ return jQuery.get(foo.htm);}function doMoreAjax(){ return jQuery.get(bar.htm);}jQuery.when( doAjax(), doMoreAjax() ) .then(function(){}) .fail(function(){});
  • 49. jQuery.sub() creates a new copy of jQuery creates a new copy of jQuery properties and methods can be modified properties and methods can be modified without affecting the original jQuery object without affecting the original jQuery object
  • 50. jQuery.sub() create encapsulated plugin APIs create encapsulated plugin APIs avoid namespace collision avoid namespace collision painless way of overriding methods painless way of overriding methods without completely destroying original code without completely destroying original code encapsulation and basic namespacing encapsulation and basic namespacing for jQuery plugins for jQuery plugins
  • 51. Example: Adding a Method(function($){ // add custom method $.fn.myCustomMethod = function(){ return just for me; }; $(document).ready(function() { $(body).myCustomMethod() // just for me });})(jQuery);typeof jQuery(body).myCustomMethod // function
  • 52. Example: Adding a Method(function($){ var sub$ = $.sub(); sub$.fn.myCustomMethod = function(){ return just for me; }; sub$(document).ready(function() { sub$(body).myCustomMethod() // just for me });})(jQuery);typeof jQuery(body).myCustomMethod // undefined
  • 53. Example: Override a Methodvar sub$ = $.sub();sub$.fn.remove = function() { // trigger a remove event this.trigger("remove"); // call original jQuery method return jQuery.fn.remove.apply( this, arguments );};
  • 54. Example: Override a Method $(".do_not_click").click(function() { $(this).remove(); }); $(document).bind("remove", function(e) { alert( "uuh ooh!" ); // never shown });  
  • 55. Example: Override a Methodsub$(function($) { $(".do_not_click").click(function() { $(this).remove(); }); $(document).bind("remove", function(e) { alert( "uuh ooh!" ); });});
  • 56. Example: Override a Method $(".do_not_click").click(function() { $sub(this).remove(); }); $(document).bind("remove", function(e) { alert( "uuh ooh!" ); });  
  • 57. Partial Isolation m e t h o d s - still point to original jQuery m e t h o d s - still point to original jQuery e v e n t s - will still be through main jQuery e v e n t s - will still be through main jQuery d a t a - is bound to elements through main jQuery d a t a - is bound to elements through main jQuery A jja x - runs through the main jQuery A a x - runs through the main jQuery ... ...
  • 58. Example: Plugin-Specific Methods(function() { // copy jQuery using sub() var plugin = jQuery.sub(); // extend copy with new methods plugin.fn.extend({ … }); // add to original jQuery jQuery.fn.myplugin = function() { // return our special plugin version return plugin( this ); };})();
  • 59. Example: Plugin-Specific Methodsplugin.fn.extend({ open: function() { return this.show(); }, close: function() { return this.hide(); }});jQuery.fn.myplugin = function() { this.addClass("plugin"); return plugin( this );};
  • 60. Example: Plugin-Specific Methods$(document).ready(function() { $(#main).open(); // does not work!});
  • 61. Example: Plugin-Specific Methods$(document).ready(function() { // call plugin // open method now exists $(#main).myplugin().open();});
  • 62. Thats it! 1.5.1 RC1 out now 1.5.1 RC1 out now 1.5.1: February 24th 1.5.1: February 24th
  • 63. Any Questions?Martin KleppeMartin Kleppe@aemkei@aemkei