SlideShare a Scribd company logo
1 of 66
Download to read offline
jQuery 1.5
Martin Kleppe @aemkei
Martin Kleppe @aemkei
http://ubilabs.net
http://ubilabs.net
What's new
 Ajax rewrite
 Ajax rewrite
 Deferred Objects
 Deferred Objects
 performance improvements
 performance improvements
 new methods
 new methods
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
CDN
http://ajax.googleapis.com/
http://ajax.googleapis.com/
ajax/libs/jquery/1 ..5 ..0 //
ajax/libs/jquery/1 5 0
jquery.min.js
jquery.min.js
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
Traversal Performance
 .children() ,, .prev() ,, .next()
 .children() .prev() .next()
 substantial speed-ups
 substantial speed-ups
Build System
 Java/Rhino ! V8/NodeJS
 Java/Rhino ! V8/NodeJS
 Google Closure Compiler ! UglifyJS
 Google Closure Compiler ! UglifyJS
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
Ajax Rewrite
 complete rewrite
 complete rewrite
 consistency across the API
 consistency across the API
Affected Methods
jQuery.ajax()        //   asynchronous HTTP request
jQuery.get()         //   load data using GET
jQuery.getJSON()     //   load JSON-encoded data
jQuery.getScript()   //   load JS file
jQuery.post()        //   load data using POST
Old School
$.ajax({ url: "/example" }, {
  success: function(){
     // horray!
  }}
);
New School
$.ajax({ url: "/example" }).
  success(
     function(){ /* horray! */}
  );
New School
$.ajax({ url: "/example" }).
  success( function(){ /* horray! */} );
Chaining Handlers
var jqxhr = $.ajax({ url: "/example" })
  .success( /* success handler */ )
  .error( /* error handler */ )
  .complete( /* 1st complete handler */ );
Further Handlers
var jqxhr = $.ajax({ url: "/example" })
  .success( /* success handler */ )

// perform other work here ...

jqxhr.success( /* 2nd success handler */ )
Abort Ajax
var jqxhr = $.ajax({ url: "/example" })
  .success( /* success handler */ );

setTimeout(function(){
  jqxhr.abort();
}, 1000);
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
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
$.ajaxPrefilter()
$.ajaxPrefilter(
  function( options, originalOptions, jqXHR ) {
    // your code here
  }
);

// originalOptions: options provided to method
// unmodified + without defaults from ajaxSettings
Handle Custom Options
var currentRequests = {};
// abort duplicated request
$.ajaxPrefilter(
  function( options, originalOptions, jqXHR ) {
    if ( options.abortOnRetry ) {
      if ( currentRequests[ options.url ] ) {
        currentRequests[ options.url ].abort();
      }
      currentRequests[ options.url ] = jqXHR;
    }
  }
);
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;
  }
});
Prefilter dataType
// prefilter to JSON and script requests
$.ajaxPrefilter( "json script", function() {
  // ...
});
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
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
Global converters
$.ajaxSetup({
  converters: {
    "text mydatatype": function( textValue ) {
      if ( valid( textValue ) ) {
        // some parsing logic here
        return mydatatypeValue;
      } else {
        // notify a parsererror
        throw exceptionObject;
      }
    }
  }
});
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
Request Data of Type "mydatatype"
$.ajax( url, {
  dataType: "mydatatype"
});
"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;
    }
  }
});
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
Data Converters in jQuery Source
// format: "source_type destination_type"
// "*" can be used for source_type
converters: {
  // 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
}
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
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
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 */
       }
    };
  }
);
Option: completeCallback
// completeCallback signature
function(
  status,      // HTTP status code
  statusText, // status text of response
  [responses], // map of dataType/value
  [headers]    // response headers
)
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 */
  }
);
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
Assign Handlers
// remember request object
var jqxhr = $.ajax({ url: "/example" })
    .success( /* success handler */ )
    .error( /* error handler */ )
    .complete( /* 1st complete handler */ );

// perform other work here ...

jqxhr.complete( /* 2nd complete handler */ );
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
jQuery.Deferred Constructor
[new] jQuery.Deferred( [method] )

// optional new keyword
// method called before constructor returns
jQuery.Deferred Constructor
function(){
  var deferred = new jQuery.Deferred();
  // asnyc code
  return deferred.promise();
}
jQuery.Deferred Example
$.wait = function(time) {
  var deferred = new jQuery.Deferred();
  setTimeout(deferred.resolve, time);
  return deferred.promise();
}
jQuery.Deferred Shorthand

 return $.Deferred(function( deferred ) {
   // your async code
 }).promise();
  
jQuery.Deferred Shorthand
$.wait = function(time) {
  return $.Deferred(function( deferred ) {
    setTimeout(deferred.resolve, time);
  }).promise();
};
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
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
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
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)
jQuery.when()
function doAjax(){
  return jQuery.get('foo.htm');
}

function doMoreAjax(){
  return jQuery.get('bar.htm');
}

jQuery.when( doAjax(), doMoreAjax() )
  .then(function(){})
  .fail(function(){});
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
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
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
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
Example: Override a Method
var sub$ = $.sub();

sub$.fn.remove = function() {
  // trigger a remove event
  this.trigger("remove");

  // call original jQuery method
  return jQuery.fn.remove.apply( this, arguments );
};
Example: Override a Method

 $(".do_not_click").click(function() {
   $(this).remove();
 });

 $(document).bind("remove", function(e) {
   alert( "uuh ooh!" ); // never shown
 });
  
Example: Override a Method
sub$(function($) {
  $(".do_not_click").click(function() {
    $(this).remove();
  });

  $(document).bind("remove", function(e) {
    alert( "uuh ooh!" );
  });
});
Example: Override a Method

 $(".do_not_click").click(function() {
   $sub(this).remove();
 });

 $(document).bind("remove", function(e) {
   alert( "uuh ooh!" );
 });
  
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
 ...
 ...
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 );
  };
})();
Example: Plugin-Specific Methods
plugin.fn.extend({
  open: function() {
     return this.show();
  },
  close: function() {
     return this.hide();
  }
});

jQuery.fn.myplugin = function() {
  this.addClass("plugin");
  return plugin( this );
};
Example: Plugin-Specific Methods
$(document).ready(function() {
  $('#main').open(); // does not work!
});
Example: Plugin-Specific Methods
$(document).ready(function() {
  // call plugin
  // open method now exists
  $('#main').myplugin().open();
});
That's it!
 1.5.1 RC1 out now
 1.5.1 RC1 out now
 1.5.1: February 24th
 1.5.1: February 24th
Any Questions?
Martin Kleppe
Martin Kleppe
@aemkei
@aemkei

More Related Content

What's hot

AngularJS Services
AngularJS ServicesAngularJS Services
AngularJS ServicesEyal Vardi
 
Using React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIsUsing React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIsMihail Gaberov
 
Higher-Order Components — Ilya Gelman
Higher-Order Components — Ilya GelmanHigher-Order Components — Ilya Gelman
Higher-Order Components — Ilya Gelman500Tech
 
React + Redux. Best practices
React + Redux.  Best practicesReact + Redux.  Best practices
React + Redux. Best practicesClickky
 
Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Konstantin Kudryashov
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and httpAlexe Bogdan
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingVisual Engineering
 
06 jQuery #burningkeyboards
06 jQuery  #burningkeyboards06 jQuery  #burningkeyboards
06 jQuery #burningkeyboardsDenis Ristic
 
Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 DreamLab
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)BoneyGawande
 
Net/http and the http.handler interface
Net/http and the http.handler interfaceNet/http and the http.handler interface
Net/http and the http.handler interfaceJoakim Gustin
 
Developing web-apps like it's 2013
Developing web-apps like it's 2013Developing web-apps like it's 2013
Developing web-apps like it's 2013Laurent_VB
 
Recompacting your react application
Recompacting your react applicationRecompacting your react application
Recompacting your react applicationGreg Bergé
 
Swift Delhi: Practical POP
Swift Delhi: Practical POPSwift Delhi: Practical POP
Swift Delhi: Practical POPNatasha Murashev
 
Asyc flow control with javascript generators - redux-saga
Asyc flow control with javascript generators - redux-sagaAsyc flow control with javascript generators - redux-saga
Asyc flow control with javascript generators - redux-sagaPedro Solá
 
Protocol-Oriented MVVM (extended edition)
Protocol-Oriented MVVM (extended edition)Protocol-Oriented MVVM (extended edition)
Protocol-Oriented MVVM (extended edition)Natasha Murashev
 

What's hot (19)

AngularJS Services
AngularJS ServicesAngularJS Services
AngularJS Services
 
Using React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIsUsing React, Redux and Saga with Lottoland APIs
Using React, Redux and Saga with Lottoland APIs
 
Higher-Order Components — Ilya Gelman
Higher-Order Components — Ilya GelmanHigher-Order Components — Ilya Gelman
Higher-Order Components — Ilya Gelman
 
React + Redux. Best practices
React + Redux.  Best practicesReact + Redux.  Best practices
React + Redux. Best practices
 
Zend framework service
Zend framework serviceZend framework service
Zend framework service
 
Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and http
 
Workshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testingWorkshop 23: ReactJS, React & Redux testing
Workshop 23: ReactJS, React & Redux testing
 
06 jQuery #burningkeyboards
06 jQuery  #burningkeyboards06 jQuery  #burningkeyboards
06 jQuery #burningkeyboards
 
Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6Workshop 10: ECMAScript 6
Workshop 10: ECMAScript 6
 
Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3 Intro to Redux | DreamLab Academy #3
Intro to Redux | DreamLab Academy #3
 
Java script advance-auroskills (2)
Java script advance-auroskills (2)Java script advance-auroskills (2)
Java script advance-auroskills (2)
 
Net/http and the http.handler interface
Net/http and the http.handler interfaceNet/http and the http.handler interface
Net/http and the http.handler interface
 
Developing web-apps like it's 2013
Developing web-apps like it's 2013Developing web-apps like it's 2013
Developing web-apps like it's 2013
 
Recompacting your react application
Recompacting your react applicationRecompacting your react application
Recompacting your react application
 
Swift Delhi: Practical POP
Swift Delhi: Practical POPSwift Delhi: Practical POP
Swift Delhi: Practical POP
 
Asyc flow control with javascript generators - redux-saga
Asyc flow control with javascript generators - redux-sagaAsyc flow control with javascript generators - redux-saga
Asyc flow control with javascript generators - redux-saga
 
Protocol-Oriented MVVM (extended edition)
Protocol-Oriented MVVM (extended edition)Protocol-Oriented MVVM (extended edition)
Protocol-Oriented MVVM (extended edition)
 
Min-Maxing Software Costs
Min-Maxing Software CostsMin-Maxing Software Costs
Min-Maxing Software Costs
 

Viewers also liked

Webfordevpresentationll
WebfordevpresentationllWebfordevpresentationll
WebfordevpresentationllITCILO
 
Vickery Eckhoff Copywriting Samples
Vickery Eckhoff Copywriting SamplesVickery Eckhoff Copywriting Samples
Vickery Eckhoff Copywriting Samplesguestd06d5a
 
Best copywriting for you!
Best copywriting for you!Best copywriting for you!
Best copywriting for you!guestd06d5a
 
Itciloaudienceresponsesystems
ItciloaudienceresponsesystemsItciloaudienceresponsesystems
ItciloaudienceresponsesystemsITCILO
 
International Training Centre of the ILO
International Training Centre of the ILOInternational Training Centre of the ILO
International Training Centre of the ILOITCILO
 
Role of vitamins in health promotion
Role of vitamins in health promotionRole of vitamins in health promotion
Role of vitamins in health promotionslideshareacount
 
Economic Stability and EU Convergence in Southeast Europe: Building Capacitie...
Economic Stability and EU Convergence in Southeast Europe: Building Capacitie...Economic Stability and EU Convergence in Southeast Europe: Building Capacitie...
Economic Stability and EU Convergence in Southeast Europe: Building Capacitie...ITCILO
 

Viewers also liked (8)

Webfordevpresentationll
WebfordevpresentationllWebfordevpresentationll
Webfordevpresentationll
 
Vickery Eckhoff Copywriting Samples
Vickery Eckhoff Copywriting SamplesVickery Eckhoff Copywriting Samples
Vickery Eckhoff Copywriting Samples
 
Best copywriting for you!
Best copywriting for you!Best copywriting for you!
Best copywriting for you!
 
Hridubai
HridubaiHridubai
Hridubai
 
Itciloaudienceresponsesystems
ItciloaudienceresponsesystemsItciloaudienceresponsesystems
Itciloaudienceresponsesystems
 
International Training Centre of the ILO
International Training Centre of the ILOInternational Training Centre of the ILO
International Training Centre of the ILO
 
Role of vitamins in health promotion
Role of vitamins in health promotionRole of vitamins in health promotion
Role of vitamins in health promotion
 
Economic Stability and EU Convergence in Southeast Europe: Building Capacitie...
Economic Stability and EU Convergence in Southeast Europe: Building Capacitie...Economic Stability and EU Convergence in Southeast Europe: Building Capacitie...
Economic Stability and EU Convergence in Southeast Europe: Building Capacitie...
 

Similar to What's new in jQuery 1.5

jQuery - Chapter 5 - Ajax
jQuery - Chapter 5 -  AjaxjQuery - Chapter 5 -  Ajax
jQuery - Chapter 5 - AjaxWebStackAcademy
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for JoomlaLuke Summerfield
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginnersDivakar Gu
 
JQuery Presentation
JQuery PresentationJQuery Presentation
JQuery PresentationSony Jain
 
Asynchronous Interfaces
Asynchronous InterfacesAsynchronous Interfaces
Asynchronous Interfacesmaccman
 
jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Foreverstephskardal
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsFrancois Zaninotto
 
AngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesAngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesEyal Vardi
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretssmueller_sandsmedia
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jscacois
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium AppsNate Abele
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashBret Little
 
Architecting JavaScript Code
Architecting JavaScript CodeArchitecting JavaScript Code
Architecting JavaScript CodeSuresh Balla
 

Similar to What's new in jQuery 1.5 (20)

jQuery - Chapter 5 - Ajax
jQuery - Chapter 5 -  AjaxjQuery - Chapter 5 -  Ajax
jQuery - Chapter 5 - Ajax
 
jQuery: Events, Animation, Ajax
jQuery: Events, Animation, AjaxjQuery: Events, Animation, Ajax
jQuery: Events, Animation, Ajax
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Ajax
AjaxAjax
Ajax
 
Rails is not just Ruby
Rails is not just RubyRails is not just Ruby
Rails is not just Ruby
 
JQuery Presentation
JQuery PresentationJQuery Presentation
JQuery Presentation
 
Asynchronous Interfaces
Asynchronous InterfacesAsynchronous Interfaces
Asynchronous Interfaces
 
jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Forever
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
 
AngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesAngularJS - $http & $resource Services
AngularJS - $http & $resource Services
 
JavaScript Lessons 2023
JavaScript Lessons 2023JavaScript Lessons 2023
JavaScript Lessons 2023
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
Server Side Swift: Vapor
Server Side Swift: VaporServer Side Swift: Vapor
Server Side Swift: Vapor
 
Building Lithium Apps
Building Lithium AppsBuilding Lithium Apps
Building Lithium Apps
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and Lodash
 
Ajax Lecture Notes
Ajax Lecture NotesAjax Lecture Notes
Ajax Lecture Notes
 
Architecting JavaScript Code
Architecting JavaScript CodeArchitecting JavaScript Code
Architecting JavaScript Code
 

More from Martin Kleppe

1024+ Seconds of JS Wizardry - JSConf.eu 2013
1024+ Seconds of JS Wizardry - JSConf.eu 20131024+ Seconds of JS Wizardry - JSConf.eu 2013
1024+ Seconds of JS Wizardry - JSConf.eu 2013Martin Kleppe
 
WhereBerlin – Interactive Visualizations in the Browser
WhereBerlin – Interactive Visualizations in the BrowserWhereBerlin – Interactive Visualizations in the Browser
WhereBerlin – Interactive Visualizations in the BrowserMartin Kleppe
 
Visualization Using the Google Maps API
Visualization Using the Google Maps APIVisualization Using the Google Maps API
Visualization Using the Google Maps APIMartin Kleppe
 
WhereCamp Berlin - Visualizing Big Geo Data
WhereCamp Berlin - Visualizing Big Geo DataWhereCamp Berlin - Visualizing Big Geo Data
WhereCamp Berlin - Visualizing Big Geo DataMartin Kleppe
 
Google Maps API - DevFest Karlsruhe
Google Maps API - DevFest Karlsruhe Google Maps API - DevFest Karlsruhe
Google Maps API - DevFest Karlsruhe Martin Kleppe
 
Ubilabs: Google Maps API - Best Practices
Ubilabs: Google Maps API - Best PracticesUbilabs: Google Maps API - Best Practices
Ubilabs: Google Maps API - Best PracticesMartin Kleppe
 

More from Martin Kleppe (6)

1024+ Seconds of JS Wizardry - JSConf.eu 2013
1024+ Seconds of JS Wizardry - JSConf.eu 20131024+ Seconds of JS Wizardry - JSConf.eu 2013
1024+ Seconds of JS Wizardry - JSConf.eu 2013
 
WhereBerlin – Interactive Visualizations in the Browser
WhereBerlin – Interactive Visualizations in the BrowserWhereBerlin – Interactive Visualizations in the Browser
WhereBerlin – Interactive Visualizations in the Browser
 
Visualization Using the Google Maps API
Visualization Using the Google Maps APIVisualization Using the Google Maps API
Visualization Using the Google Maps API
 
WhereCamp Berlin - Visualizing Big Geo Data
WhereCamp Berlin - Visualizing Big Geo DataWhereCamp Berlin - Visualizing Big Geo Data
WhereCamp Berlin - Visualizing Big Geo Data
 
Google Maps API - DevFest Karlsruhe
Google Maps API - DevFest Karlsruhe Google Maps API - DevFest Karlsruhe
Google Maps API - DevFest Karlsruhe
 
Ubilabs: Google Maps API - Best Practices
Ubilabs: Google Maps API - Best PracticesUbilabs: Google Maps API - Best Practices
Ubilabs: Google Maps API - Best Practices
 

Recently uploaded

Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 

Recently uploaded (20)

Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 

What's new in jQuery 1.5

  • 1. jQuery 1.5 Martin Kleppe @aemkei Martin Kleppe @aemkei http://ubilabs.net http://ubilabs.net
  • 2. What's 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
  • 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.
  • 8.
  • 9.
  • 10. Build System Java/Rhino ! V8/NodeJS Java/Rhino ! V8/NodeJS Google Closure Compiler ! UglifyJS Google Closure Compiler ! UglifyJS
  • 11. 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
  • 12. Ajax Rewrite complete rewrite complete rewrite consistency across the API consistency across the API
  • 13. Affected Methods jQuery.ajax() // asynchronous HTTP request jQuery.get() // load data using GET jQuery.getJSON() // load JSON-encoded data jQuery.getScript() // load JS file jQuery.post() // load data using POST
  • 14. Old School $.ajax({ url: "/example" }, { success: function(){ // horray! }} );
  • 15. New School $.ajax({ url: "/example" }). success( function(){ /* horray! */} );
  • 16. New School $.ajax({ url: "/example" }). success( function(){ /* horray! */} );
  • 17. Chaining Handlers var jqxhr = $.ajax({ url: "/example" }) .success( /* success handler */ ) .error( /* error handler */ ) .complete( /* 1st complete handler */ );
  • 18. Further Handlers var jqxhr = $.ajax({ url: "/example" }) .success( /* success handler */ ) // perform other work here ... jqxhr.success( /* 2nd success handler */ )
  • 19. Abort Ajax var jqxhr = $.ajax({ url: "/example" }) .success( /* success handler */ ); setTimeout(function(){ jqxhr.abort(); }, 1000);
  • 20. 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
  • 21. 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
  • 22. $.ajaxPrefilter() $.ajaxPrefilter( function( options, originalOptions, jqXHR ) { // your code here } ); // originalOptions: options provided to method // unmodified + without defaults from ajaxSettings
  • 23. Handle Custom Options var currentRequests = {}; // abort duplicated request $.ajaxPrefilter( function( options, originalOptions, jqXHR ) { if ( options.abortOnRetry ) { if ( currentRequests[ options.url ] ) { currentRequests[ options.url ].abort(); } currentRequests[ options.url ] = jqXHR; } } );
  • 24. 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; } });
  • 25. Prefilter dataType // prefilter to JSON and script requests $.ajaxPrefilter( "json script", function() { // ... });
  • 26. 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
  • 27. 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
  • 28. Global converters $.ajaxSetup({ converters: { "text mydatatype": function( textValue ) { if ( valid( textValue ) ) { // some parsing logic here return mydatatypeValue; } else { // notify a parsererror throw exceptionObject; } } } });
  • 29. 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
  • 30. Request Data of Type "mydatatype" $.ajax( url, { dataType: "mydatatype" });
  • 31. "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; } } });
  • 32. 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
  • 33. Data Converters in jQuery Source // format: "source_type destination_type" // "*" can be used for source_type converters: { // 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 }
  • 34. 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
  • 35. 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
  • 36. 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 */ } }; } );
  • 37. Option: completeCallback // completeCallback signature function( status, // HTTP status code statusText, // status text of response [responses], // map of dataType/value [headers] // response headers )
  • 38. 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 */ } );
  • 39. 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
  • 40. Assign Handlers // remember request object var jqxhr = $.ajax({ url: "/example" }) .success( /* success handler */ ) .error( /* error handler */ ) .complete( /* 1st complete handler */ ); // perform other work here ... jqxhr.complete( /* 2nd complete handler */ );
  • 41. 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
  • 42. jQuery.Deferred Constructor [new] jQuery.Deferred( [method] ) // optional new keyword // method called before constructor returns
  • 43. jQuery.Deferred Constructor function(){ var deferred = new jQuery.Deferred(); // asnyc code return deferred.promise(); }
  • 44. jQuery.Deferred Example $.wait = function(time) { var deferred = new jQuery.Deferred(); setTimeout(deferred.resolve, time); return deferred.promise(); }
  • 45. jQuery.Deferred Shorthand return $.Deferred(function( deferred ) { // your async code }).promise();  
  • 46. jQuery.Deferred Shorthand $.wait = function(time) { return $.Deferred(function( deferred ) { setTimeout(deferred.resolve, time); }).promise(); };
  • 47. 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
  • 48. 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
  • 49. 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
  • 50. 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)
  • 51. jQuery.when() function doAjax(){ return jQuery.get('foo.htm'); } function doMoreAjax(){ return jQuery.get('bar.htm'); } jQuery.when( doAjax(), doMoreAjax() ) .then(function(){}) .fail(function(){});
  • 52. 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
  • 53. 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
  • 54. 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
  • 55. 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
  • 56. Example: Override a Method var sub$ = $.sub(); sub$.fn.remove = function() { // trigger a remove event this.trigger("remove"); // call original jQuery method return jQuery.fn.remove.apply( this, arguments ); };
  • 57. Example: Override a Method $(".do_not_click").click(function() { $(this).remove(); }); $(document).bind("remove", function(e) { alert( "uuh ooh!" ); // never shown });  
  • 58. Example: Override a Method sub$(function($) { $(".do_not_click").click(function() { $(this).remove(); }); $(document).bind("remove", function(e) { alert( "uuh ooh!" ); }); });
  • 59. Example: Override a Method $(".do_not_click").click(function() { $sub(this).remove(); }); $(document).bind("remove", function(e) { alert( "uuh ooh!" ); });  
  • 60. 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 ... ...
  • 61. 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 ); }; })();
  • 62. Example: Plugin-Specific Methods plugin.fn.extend({ open: function() { return this.show(); }, close: function() { return this.hide(); } }); jQuery.fn.myplugin = function() { this.addClass("plugin"); return plugin( this ); };
  • 63. Example: Plugin-Specific Methods $(document).ready(function() { $('#main').open(); // does not work! });
  • 64. Example: Plugin-Specific Methods $(document).ready(function() { // call plugin // open method now exists $('#main').myplugin().open(); });
  • 65. That's it! 1.5.1 RC1 out now 1.5.1 RC1 out now 1.5.1: February 24th 1.5.1: February 24th
  • 66. Any Questions? Martin Kleppe Martin Kleppe @aemkei @aemkei