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

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 Ajaxrewrite Ajax rewrite Deferred Objects Deferred Objects performance improvements performance improvements new methods new methods
  • 3.
    Stats 207 kbregular 207 kb regular 29 kb minified gzip 29 kb minified gzip 83 fixed bugs 83 fixed bugs 460 closed tickets 460 closed tickets
  • 4.
  • 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
  • 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 completerewrite 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 re 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 beforeeach 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 varcurrentRequests = {}; // 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 // prefilterto 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 responseof 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 tointroduce 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 ofType "mydatatype" $.ajax( url, { dataType: "mydatatype" });
  • 31.
    "Inline" Converters // requestsXML 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 DataTypes 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 injQuery 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 advancedway 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 requestrequires 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 // completeCallbacksignature function( status, // HTTP status code statusText, // status text of response [responses], // map of dataType/value [headers] // response headers )
  • 38.
    Attach to SpecificdataType // 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 withreturn 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 // rememberrequest 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 callbackfunctions 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 anew 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 encapsulatedplugin 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 aMethod (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 aMethod (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 aMethod 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 aMethod $(".do_not_click").click(function() { $(this).remove(); }); $(document).bind("remove", function(e) { alert( "uuh ooh!" ); // never shown });  
  • 58.
    Example: Override aMethod sub$(function($) { $(".do_not_click").click(function() { $(this).remove(); }); $(document).bind("remove", function(e) { alert( "uuh ooh!" ); }); });
  • 59.
    Example: Override aMethod $(".do_not_click").click(function() { $sub(this).remove(); }); $(document).bind("remove", function(e) { alert( "uuh ooh!" ); });  
  • 60.
    Partial Isolation me 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.1RC1 out now 1.5.1 RC1 out now 1.5.1: February 24th 1.5.1: February 24th
  • 66.