what's new in jquery 1.5
DESCRIPTION
A quick introduction to jQuery 1.5 by Martin Kleppe. He gave this talk at the Hamburg JavaScript User Group @hhjs.TRANSCRIPT
jQuery 1.5jQuery 1.5jQuery 1.5jQuery 1.5jQuery 1.5Martin Kleppe @aemkeiMartin Kleppe @aemkeiMartin Kleppe @aemkeiMartin Kleppe @aemkeiMartin Kleppe @aemkeihttp://ubilabs.nethttp://ubilabs.nethttp://ubilabs.nethttp://ubilabs.nethttp://ubilabs.net
What's newWhat's newWhat's newWhat's newWhat's new
Ajax rewriteAjax rewriteAjax rewriteAjax rewriteAjax rewrite
Deferred ObjectsDeferred ObjectsDeferred ObjectsDeferred ObjectsDeferred Objects
performance improvementsperformance improvementsperformance improvementsperformance improvementsperformance improvements
new methodsnew methodsnew methodsnew methodsnew methods
StatsStatsStatsStatsStats
207 kb regular207 kb regular207 kb regular207 kb regular207 kb regular
29 kb minified gzip29 kb minified gzip29 kb minified gzip29 kb minified gzip29 kb minified gzip
83 fixed bugs83 fixed bugs83 fixed bugs83 fixed bugs83 fixed bugs
460 closed tickets460 closed tickets460 closed tickets460 closed tickets460 closed tickets
CDNCDNCDNCDNCDN
http://ajax.googleapis.com/http://ajax.googleapis.com/http://ajax.googleapis.com/http://ajax.googleapis.com/http://ajax.googleapis.com/
ajax/libs/jquery/ajax/libs/jquery/ajax/libs/jquery/ajax/libs/jquery/ajax/libs/jquery/11..55..0011..55..0011..55..0011..55..0011..55..00/////jquery.min.jsjquery.min.jsjquery.min.jsjquery.min.jsjquery.min.js
CDN Minor VersionCDN Minor VersionCDN Minor VersionCDN Minor VersionCDN Minor Version
http://ajax.googleapis.com/http://ajax.googleapis.com/http://ajax.googleapis.com/http://ajax.googleapis.com/http://ajax.googleapis.com/
ajax/libs/jquery/ajax/libs/jquery/ajax/libs/jquery/ajax/libs/jquery/ajax/libs/jquery/11..5511..5511..5511..5511..55/////jquery.min.jsjquery.min.jsjquery.min.jsjquery.min.jsjquery.min.js
Traversal PerformanceTraversal PerformanceTraversal PerformanceTraversal PerformanceTraversal Performance
.children().children().children().children().children() , , , , , .prev().prev().prev().prev().prev() , , , , , .next().next().next().next().next()substantial speed-upssubstantial speed-upssubstantial speed-upssubstantial speed-upssubstantial speed-ups
Build SystemBuild SystemBuild SystemBuild SystemBuild System
Java/Rhino ! V8/NodeJSJava/Rhino ! V8/NodeJSJava/Rhino ! V8/NodeJSJava/Rhino ! V8/NodeJSJava/Rhino ! V8/NodeJS
Google Closure Compiler ! UglifyJSGoogle Closure Compiler ! UglifyJSGoogle Closure Compiler ! UglifyJSGoogle Closure Compiler ! UglifyJSGoogle Closure Compiler ! UglifyJS
New MethodsNew MethodsNew MethodsNew MethodsNew Methods
$.parseXML()$.parseXML()$.parseXML()$.parseXML()$.parseXML()Parses string into XMLParses string into XMLParses string into XMLParses string into XMLParses string into XML
.clone( true, true ).clone( true, true ).clone( true, true ).clone( true, true ).clone( true, true )Clone Clone Clone Clone Clone deepdeepdeepdeepdeep with data and events with data and events with data and events with data and events with data and events
Ajax RewriteAjax RewriteAjax RewriteAjax RewriteAjax Rewrite
complete rewritecomplete rewritecomplete rewritecomplete rewritecomplete rewrite
consistency across the APIconsistency across the APIconsistency across the APIconsistency across the APIconsistency across the API
Affected MethodsAffected MethodsAffected MethodsAffected MethodsAffected Methods
jQueryjQuery..ajaxajax()() // asynchronous HTTP request// asynchronous HTTP requestjQueryjQuery..getget()() // load data using GET// load data using GETjQueryjQuery..getJSONgetJSON()() // load JSON-encoded data// load JSON-encoded datajQueryjQuery..getScriptgetScript()() // load JS file// load JS filejQueryjQuery..postpost()() // load data using POST// load data using POST
Old SchoolOld SchoolOld SchoolOld SchoolOld School
$$..ajaxajax(({{ url url:: "/example""/example" }},, {{ success success:: functionfunction()(){{ // horray!// horray! }}}}););
New SchoolNew SchoolNew SchoolNew SchoolNew School
$$..ajaxajax(({{ url url:: "/example""/example" }}).). successsuccess(( functionfunction()(){{ /* horray! *//* horray! */}} ););
New SchoolNew SchoolNew SchoolNew SchoolNew School
$$..ajaxajax(({{ url url:: "/example""/example" }}).). successsuccess(( functionfunction()(){{ /* horray! *//* horray! */}} ););
Chaining HandlersChaining HandlersChaining HandlersChaining HandlersChaining Handlers
varvar jqxhr jqxhr == $ $..ajaxajax(({{ url url:: "/example""/example" }})) ..successsuccess(( /* success handler *//* success handler */ )) ..errorerror(( /* error handler *//* error handler */ )) ..completecomplete(( /* 1st complete handler *//* 1st complete handler */ ););
Further HandlersFurther HandlersFurther HandlersFurther HandlersFurther Handlers
varvar jqxhr jqxhr == $ $..ajaxajax(({{ url url:: "/example""/example" }})) ..successsuccess(( /* success handler *//* success handler */ ))
// perform other work here ...// perform other work here ...
jqxhrjqxhr..successsuccess(( /* 2nd success handler *//* 2nd success handler */ ))
Abort AjaxAbort AjaxAbort AjaxAbort AjaxAbort Ajax
varvar jqxhr jqxhr == $ $..ajaxajax(({{ url url:: "/example""/example" }})) ..successsuccess(( /* success handler *//* success handler */ ););
setTimeoutsetTimeout((functionfunction()(){{ jqxhr jqxhr..abortabort();();}},, 10001000););
ExtensibleExtensibleExtensibleExtensibleExtensible
PPrreeffiilltteerrssPPrreeffiilltteerrssPPrreeffiilltteerrssPPrreeffiilltteerrssPPrreeffiilltteerrss - beforeSend callbacks - beforeSend callbacks - beforeSend callbacks - beforeSend callbacks - beforeSend callbacks
CCoonnvveerrtteerrssCCoonnvveerrtteerrssCCoonnvveerrtteerrssCCoonnvveerrtteerrssCCoonnvveerrtteerrss - dataFilter callbacks - dataFilter callbacks - dataFilter callbacks - dataFilter callbacks - dataFilter callbacks
TTrraannssppoorrttssTTrraannssppoorrttssTTrraannssppoorrttssTTrraannssppoorrttssTTrraannssppoorrttss - used internally - used internally - used internally - used internally - used internally
PrefiltersPrefiltersPrefiltersPrefiltersPrefilters
called before each request is sentcalled before each request is sentcalled before each request is sentcalled before each request is sentcalled before each request is sent
prior to any $.ajax() option handlingprior to any $.ajax() option handlingprior to any $.ajax() option handlingprior to any $.ajax() option handlingprior to any $.ajax() option handling
$.ajaxPrefilter()$.ajaxPrefilter()$.ajaxPrefilter()$.ajaxPrefilter()$.ajaxPrefilter()
$$..ajaxPrefilterajaxPrefilter(( functionfunction(( options options,, originalOptions originalOptions,, jqXHR jqXHR )) {{ // your code here// your code here }}););
// originalOptions: options provided to method // originalOptions: options provided to method // unmodified + without defaults from ajaxSettings// unmodified + without defaults from ajaxSettings
Handle Custom OptionsHandle Custom OptionsHandle Custom OptionsHandle Custom OptionsHandle Custom Options
varvar currentRequests currentRequests == {}{};;// abort duplicated request// abort duplicated request$$..ajaxPrefilterajaxPrefilter(( functionfunction(( options options,, originalOptions originalOptions,, jqXHR jqXHR )) {{ ifif (( options options..abortOnRetry abortOnRetry )) {{ ifif (( currentRequests currentRequests[[ options options..url url ]] )) {{ currentRequests currentRequests[[ options options..url url ].].abortabort();(); }} currentRequests currentRequests[[ options options..url url ]] == jqXHR jqXHR;; }} }}););
Modify Existing OptionsModify Existing OptionsModify Existing OptionsModify Existing OptionsModify Existing Options
// cross-domain proxy// cross-domain proxy$$..ajaxPrefilterajaxPrefilter(( functionfunction(( options options )) {{ ifif (( options options..crossDomain crossDomain )) {{ varvar url url == eennccooddeeUURRIICCoommppoonneenntteennccooddeeUURRIICCoommppoonneenntt(( options options..url url );); options options..url url == "/proxy?url=""/proxy?url=" ++ url url;; options options..crossDomain crossDomain == falsefalse;; }}}}););
Prefilter dataTypePrefilter dataTypePrefilter dataTypePrefilter dataTypePrefilter dataType
// prefilter to JSON and script requests// prefilter to JSON and script requests$$..ajaxPrefilterajaxPrefilter(( "json script""json script",, functionfunction()() {{ // ...// ...}}););
Modify Target dataTypeModify Target dataTypeModify Target dataTypeModify Target dataTypeModify Target dataType
// set a request as "script"// set a request as "script"
$$..ajaxPrefilterajaxPrefilter((functionfunction(( options options )) {{ ifif (( isActuallyScriptisActuallyScript(( options options..url url )) )) {{ returnreturn "script""script";; }}}}););
// all prefilters attached to "script" dataType // all prefilters attached to "script" dataType // would be applied to it// would be applied to it
ConvertersConvertersConvertersConvertersConverters
handle response of certain dataTypehandle response of certain dataTypehandle response of certain dataTypehandle response of certain dataTypehandle response of certain dataType
while another dataType is expectedwhile another dataType is expectedwhile another dataType is expectedwhile another dataType is expectedwhile another dataType is expected
stored into stored into stored into stored into stored into ajaxSettingsajaxSettingsajaxSettingsajaxSettingsajaxSettings
can be added globallycan be added globallycan be added globallycan be added globallycan be added globally
Global convertersGlobal convertersGlobal convertersGlobal convertersGlobal converters
$$..ajaxSetupajaxSetup(({{ converters converters:: {{ "text mydatatype""text mydatatype":: functionfunction(( textValue textValue )) {{ ifif (( validvalid(( textValue textValue )) )) {{ // some parsing logic here// some parsing logic here returnreturn mydatatypeValue mydatatypeValue;; }} elseelse {{ // notify a parsererror // notify a parsererror throwthrow exceptionObject exceptionObject;; }} }} }}}}););
ConvertersConvertersConvertersConvertersConverters
useful to introduce custom dataTypesuseful to introduce custom dataTypesuseful to introduce custom dataTypesuseful to introduce custom dataTypesuseful to introduce custom dataTypes
can be used to transform data into desired formatscan be used to transform data into desired formatscan be used to transform data into desired formatscan be used to transform data into desired formatscan be used to transform data into desired formats
Note: custom dataTypes must be lowercaseNote: custom dataTypes must be lowercaseNote: custom dataTypes must be lowercaseNote: custom dataTypes must be lowercaseNote: custom dataTypes must be lowercase
Request Data of Type "mydatatype"Request Data of Type "mydatatype"Request Data of Type "mydatatype"Request Data of Type "mydatatype"Request Data of Type "mydatatype"
$$..ajaxajax(( url url,, {{ dataType dataType:: "mydatatype""mydatatype"}}););
"Inline" Converters"Inline" Converters"Inline" Converters"Inline" Converters"Inline" Converters
// requests XML document// requests XML document$$..ajaxajax(( url url,, {{ dataType dataType:: "xml text mydatatype""xml text mydatatype",, converters converters:: {{ "xml text""xml text":: functionfunction(( xmlValue xmlValue )) {{ // extract relevant text from XML// extract relevant text from XML // parses it as "mydatatype"// parses it as "mydatatype" returnreturn textValue textValue;; }} }}}}););
Handling Custom Data TypesHandling Custom Data TypesHandling Custom Data TypesHandling Custom Data TypesHandling Custom Data Types
Standard dataTypes: "text", "json", "xml", "html"Standard dataTypes: "text", "json", "xml", "html"Standard dataTypes: "text", "json", "xml", "html"Standard dataTypes: "text", "json", "xml", "html"Standard dataTypes: "text", "json", "xml", "html"
Use converters option in Use converters option in Use converters option in Use converters option in Use converters option in $.ajaxSetup()$.ajaxSetup()$.ajaxSetup()$.ajaxSetup()$.ajaxSetup()to modify data type conversion strategiesto modify data type conversion strategiesto modify data type conversion strategiesto modify data type conversion strategiesto modify data type conversion strategies
Data Converters in jQuery SourceData Converters in jQuery SourceData Converters in jQuery SourceData Converters in jQuery SourceData Converters in jQuery Source
// format: "source_type destination_type"// format: "source_type destination_type"// "*" can be used for source_type// "*" can be used for source_typeconvertersconverters:: {{ // Convert anything to text// Convert anything to text "* text""* text":: window window..SSttrriinnggSSttrriinngg,, // Text to html (true = no transformation)// Text to html (true = no transformation) "text html""text html":: truetrue,, // Evaluate text as a json expression// Evaluate text as a json expression "text json""text json":: jQuery jQuery..parseJSONparseJSON,, // Parse text as xml// Parse text as xml "text xml""text xml":: jQuery jQuery..parseXMLparseXML}}
TransportsTransportsTransportsTransportsTransports
most advanced way to enhance most advanced way to enhance most advanced way to enhance most advanced way to enhance most advanced way to enhance $.ajax()$.ajax()$.ajax()$.ajax()$.ajax()
used internally by used internally by used internally by used internally by used internally by $.ajax()$.ajax()$.ajax()$.ajax()$.ajax() to issue requests to issue requests to issue requests to issue requests to issue requests
should be used only as a last resortshould be used only as a last resortshould be used only as a last resortshould be used only as a last resortshould be used only as a last resort
when prefilters and converters are insufficientwhen prefilters and converters are insufficientwhen prefilters and converters are insufficientwhen prefilters and converters are insufficientwhen prefilters and converters are insufficient
object with two methods: object with two methods: object with two methods: object with two methods: object with two methods: sendsendsendsendsend and and and and and abortabortabortabortabort
TransportsTransportsTransportsTransportsTransports
each request requires its own instanceeach request requires its own instanceeach request requires its own instanceeach request requires its own instanceeach request requires its own instance
tranports cannot be registered directlytranports cannot be registered directlytranports cannot be registered directlytranports cannot be registered directlytranports cannot be registered directly
registered using registered using registered using registered using registered using $.ajaxTransport()$.ajaxTransport()$.ajaxTransport()$.ajaxTransport()$.ajaxTransport()
provide a function that returns transport insteadprovide a function that returns transport insteadprovide a function that returns transport insteadprovide a function that returns transport insteadprovide a function that returns transport instead
Transports factoriesTransports factoriesTransports factoriesTransports factoriesTransports factories
$$..ajaxTransportajaxTransport(( functionfunction(( options options,, originalOptions originalOptions,, jqXHR jqXHR )) {{ returnreturn {{ send send:: functionfunction(( headers headers,, completeCallback completeCallback )) {{ // headers: map of request headers// headers: map of request headers // completeCallback: notify of completion// completeCallback: notify of completion }},, abort abort:: functionfunction()() {{ /* abort code *//* abort code */ }} }};; }}););
Option: completeCallbackOption: completeCallbackOption: completeCallbackOption: completeCallbackOption: completeCallback
// completeCallback signature// completeCallback signaturefunctionfunction(( status status,, // HTTP status code// HTTP status code statusText statusText,, // status text of response // status text of response [[responsesresponses],], // map of dataType/value // map of dataType/value [[headersheaders]] // response headers// response headers))
Attach to Specific dataTypeAttach to Specific dataTypeAttach to Specific dataTypeAttach to Specific dataTypeAttach to Specific dataType
// can be attached to specific dataType// can be attached to specific dataType// just like prefilters// just like prefilters
$$..ajaxTransportajaxTransport(( "script""script",, functionfunction(( options options,, originalOptions originalOptions,, jqXHR jqXHR )) {{ /* only be called for script requests *//* only be called for script requests */ }}););
jQuery.DeferredjQuery.DeferredjQuery.DeferredjQuery.DeferredjQuery.Deferred
work with return values that may not bework with return values that may not bework with return values that may not bework with return values that may not bework with return values that may not be
immediately presentimmediately presentimmediately presentimmediately presentimmediately present
chainable utility objectchainable utility objectchainable utility objectchainable utility objectchainable utility object
register multiple callbacks (callback queues)register multiple callbacks (callback queues)register multiple callbacks (callback queues)register multiple callbacks (callback queues)register multiple callbacks (callback queues)
relay on relay on relay on relay on relay on successsuccesssuccesssuccesssuccess or or or or or failurefailurefailurefailurefailure state state state state state
Assign HandlersAssign HandlersAssign HandlersAssign HandlersAssign Handlers
// remember request object// remember request objectvarvar jqxhr jqxhr == $ $..ajaxajax(({{ url url:: "/example""/example" }})) ..successsuccess(( /* success handler *//* success handler */ )) ..errorerror(( /* error handler *//* error handler */ )) ..completecomplete(( /* 1st complete handler *//* 1st complete handler */ ););
// perform other work here ...// perform other work here ...
jqxhrjqxhr..completecomplete(( /* 2nd complete handler *//* 2nd complete handler */ ););
jQuery.DeferredjQuery.DeferredjQuery.DeferredjQuery.DeferredjQuery.Deferred
then()then()then()then()then() , , , , , done()done()done()done()done() , , , , , failfailfailfailfail - functions to be called - functions to be called - functions to be called - functions to be called - functions to be called
resolveresolveresolveresolveresolve , , , , , rejectrejectrejectrejectreject - “call” them with your arguments - “call” them with your arguments - “call” them with your arguments - “call” them with your arguments - “call” them with your arguments
state stays once it has been resolvedstate stays once it has been resolvedstate stays once it has been resolvedstate stays once it has been resolvedstate stays once it has been resolved
eg: second call to eg: second call to eg: second call to eg: second call to eg: second call to resolveresolveresolveresolveresolve is ignored is ignored is ignored is ignored is ignored
functions added later are called immediatelyfunctions added later are called immediatelyfunctions added later are called immediatelyfunctions added later are called immediatelyfunctions added later are called immediately
jQuery.Deferred ConstructorjQuery.Deferred ConstructorjQuery.Deferred ConstructorjQuery.Deferred ConstructorjQuery.Deferred Constructor
[[newnew]] jQuery jQuery..DeferredDeferred(( [[methodmethod]] ))
// optional new keyword// optional new keyword// method called before constructor returns// method called before constructor returns
jQuery.Deferred ConstructorjQuery.Deferred ConstructorjQuery.Deferred ConstructorjQuery.Deferred ConstructorjQuery.Deferred Constructor
functionfunction()(){{ varvar deferred deferred == newnew jQuery jQuery..DeferredDeferred();(); // asnyc code// asnyc code returnreturn deferred deferred..promisepromise();();}}
jQuery.Deferred ExamplejQuery.Deferred ExamplejQuery.Deferred ExamplejQuery.Deferred ExamplejQuery.Deferred Example
$$..wait wait == functionfunction((timetime)) {{ varvar deferred deferred == newnew jQuery jQuery..DeferredDeferred();(); setTimeoutsetTimeout((deferreddeferred..resolveresolve,, time time);); returnreturn deferred deferred..promisepromise();();}}
jQuery.Deferred ShorthandjQuery.Deferred ShorthandjQuery.Deferred ShorthandjQuery.Deferred ShorthandjQuery.Deferred Shorthand
returnreturn $ $..DeferredDeferred((functionfunction(( deferred deferred )) {{ // your async code// your async code }}).).promisepromise();();
jQuery.Deferred ShorthandjQuery.Deferred ShorthandjQuery.Deferred ShorthandjQuery.Deferred ShorthandjQuery.Deferred Shorthand
$$..wait wait == functionfunction((timetime)) {{ returnreturn $ $..DeferredDeferred((functionfunction(( deferred deferred )) {{ setTimeoutsetTimeout((deferreddeferred..resolveresolve,, time time);); }}).).promisepromise();();}};;
Deferred Live CycleDeferred Live CycleDeferred Live CycleDeferred Live CycleDeferred Live Cycle
starts in the starts in the starts in the starts in the starts in the uunnrreessoollvveedduunnrreessoollvveedduunnrreessoollvveedduunnrreessoollvveedduunnrreessoollvveedd state state state state state
callbacks are queued to be executed latercallbacks are queued to be executed latercallbacks are queued to be executed latercallbacks are queued to be executed latercallbacks are queued to be executed later
resolveresolveresolveresolveresolve transitions into transitions into transitions into transitions into transitions into rreessoollvveeddrreessoollvveeddrreessoollvveeddrreessoollvveeddrreessoollvveedd state state state state state
immediately executes any doneCallbacksimmediately executes any doneCallbacksimmediately executes any doneCallbacksimmediately executes any doneCallbacksimmediately executes any doneCallbacks
rejectrejectrejectrejectreject transitions into transitions into transitions into transitions into transitions into rreejjeecctteeddrreejjeecctteeddrreejjeecctteeddrreejjeecctteeddrreejjeecctteedd state state state state state
immediately executes any failCallbacksimmediately executes any failCallbacksimmediately executes any failCallbacksimmediately executes any failCallbacksimmediately executes any failCallbacks
after transitions, it stays in that stateafter transitions, it stays in that stateafter transitions, it stays in that stateafter transitions, it stays in that stateafter transitions, it stays in that state
callbacks now execute immediatelycallbacks now execute immediatelycallbacks now execute immediatelycallbacks now execute immediatelycallbacks now execute immediately
Deferred Objects MethodsDeferred Objects MethodsDeferred Objects MethodsDeferred Objects MethodsDeferred Objects Methods
.done().done().done().done().done() - called when state is resolved - called when state is resolved - called when state is resolved - called when state is resolved - called when state is resolved
.fail().fail().fail().fail().fail() - called when state is rejected - called when state is rejected - called when state is rejected - called when state is rejected - called when state is rejected
.then().then().then().then().then() - called when state is resolved or rejected - called when state is resolved or rejected - called when state is resolved or rejected - called when state is resolved or rejected - called when state is resolved or rejected
.isRejected().isRejected().isRejected().isRejected().isRejected() - determine rejected state - determine rejected state - determine rejected state - determine rejected state - determine rejected state
.isResolved().isResolved().isResolved().isResolved().isResolved() - determine resolved state - determine resolved state - determine resolved state - determine resolved state - determine resolved state
Deferred Objects MethodsDeferred Objects MethodsDeferred Objects MethodsDeferred Objects MethodsDeferred Objects Methods
.reject().reject().reject().reject().reject() - reject and call failCallbacks - reject and call failCallbacks - reject and call failCallbacks - reject and call failCallbacks - reject and call failCallbacks
.rejectWith().rejectWith().rejectWith().rejectWith().rejectWith() - reject with context - reject with context - reject with context - reject with context - reject with context
.resolve().resolve().resolve().resolve().resolve() - resolve and call doneCallbacks - resolve and call doneCallbacks - resolve and call doneCallbacks - resolve and call doneCallbacks - resolve and call doneCallbacks
.resolveWith().resolveWith().resolveWith().resolveWith().resolveWith() - resolve with context - resolve with context - resolve with context - resolve with context - resolve with context
jQuery.when()jQuery.when()jQuery.when()jQuery.when()jQuery.when()
execute callback functionsexecute callback functionsexecute callback functionsexecute callback functionsexecute callback functions
based on one or more objectsbased on one or more objectsbased on one or more objectsbased on one or more objectsbased on one or more objects
usually Deferred objectsusually Deferred objectsusually Deferred objectsusually Deferred objectsusually Deferred objects
(represent asynchronous events)(represent asynchronous events)(represent asynchronous events)(represent asynchronous events)(represent asynchronous events)
jQuery.when()jQuery.when()jQuery.when()jQuery.when()jQuery.when()
functionfunction doAjaxdoAjax()(){{ returnreturn jQuery jQuery..getget(('foo.htm''foo.htm'););}}
functionfunction doMoreAjaxdoMoreAjax()(){{ returnreturn jQuery jQuery..getget(('bar.htm''bar.htm'););}}
jQueryjQuery..whenwhen(( doAjaxdoAjax(),(), doMoreAjaxdoMoreAjax()() )) ..thenthen((functionfunction()(){}{})) ..failfail((functionfunction()(){}{}););
jQuery.sub()jQuery.sub()jQuery.sub()jQuery.sub()jQuery.sub()
creates a new copy of creates a new copy of creates a new copy of creates a new copy of creates a new copy of jQueryjQueryjQueryjQueryjQuery
properties and methods can be modifiedproperties and methods can be modifiedproperties and methods can be modifiedproperties and methods can be modifiedproperties and methods can be modified
without affecting the original without affecting the original without affecting the original without affecting the original without affecting the original jQueryjQueryjQueryjQueryjQuery object object object object object
jQuery.sub()jQuery.sub()jQuery.sub()jQuery.sub()jQuery.sub()
create encapsulated plugin APIscreate encapsulated plugin APIscreate encapsulated plugin APIscreate encapsulated plugin APIscreate encapsulated plugin APIs
avoid namespace collisionavoid namespace collisionavoid namespace collisionavoid namespace collisionavoid namespace collision
painless way of overriding methodspainless way of overriding methodspainless way of overriding methodspainless way of overriding methodspainless way of overriding methods
without completely destroying original codewithout completely destroying original codewithout completely destroying original codewithout completely destroying original codewithout completely destroying original code
encapsulation and basic namespacingencapsulation and basic namespacingencapsulation and basic namespacingencapsulation and basic namespacingencapsulation and basic namespacing
for jQuery pluginsfor jQuery pluginsfor jQuery pluginsfor jQuery pluginsfor jQuery plugins
Example: Adding a MethodExample: Adding a MethodExample: Adding a MethodExample: Adding a MethodExample: Adding a Method
((functionfunction(($$)){{ // add custom method // add custom method
$ $..fnfn..myCustomMethod myCustomMethod == functionfunction()(){{ returnreturn 'just for me''just for me';; }};;
$ $((documentdocument).).readyready((functionfunction()() {{ $ $(('body''body').).myCustomMethodmyCustomMethod()() // 'just for me'// 'just for me' }}););}})()(jQueryjQuery););
typeoftypeof jQueryjQuery(('body''body').).myCustomMethod myCustomMethod // function// function
Example: Adding a MethodExample: Adding a MethodExample: Adding a MethodExample: Adding a MethodExample: Adding a Method
((functionfunction(($$)){{ varvar sub$ sub$ == $ $..subsub();();
sub$ sub$..fnfn..myCustomMethod myCustomMethod == functionfunction()(){{ returnreturn 'just for me''just for me';; }};;
sub$ sub$((documentdocument).).readyready((functionfunction()() {{ sub$ sub$(('body''body').).myCustomMethodmyCustomMethod()() // 'just for me'// 'just for me' }}););}})()(jQueryjQuery););
typeoftypeof jQueryjQuery(('body''body').).myCustomMethod myCustomMethod // undefined// undefined
Example: Override a MethodExample: Override a MethodExample: Override a MethodExample: Override a MethodExample: Override a Method
varvar sub$ sub$ == $ $..subsub();();
sub$sub$..fnfn..remove remove == functionfunction()() {{ // trigger a remove event// trigger a remove event thisthis..triggertrigger(("remove""remove"););
// call original jQuery method// call original jQuery method returnreturn jQuery jQuery..fnfn..removeremove..applyapply(( thisthis,, argumentsarguments ););}};;
Example: Override a MethodExample: Override a MethodExample: Override a MethodExample: Override a MethodExample: Override a Method
$ $((".do_not_click"".do_not_click").).clickclick((functionfunction()() {{ $ $((thisthis).).removeremove();(); }}););
$ $((documentdocument).).bindbind(("remove""remove",, functionfunction((ee)) {{ alertalert(( "uuh ooh!""uuh ooh!" );); // never shown// never shown }}););
Example: Override a MethodExample: Override a MethodExample: Override a MethodExample: Override a MethodExample: Override a Method
sub$sub$((functionfunction(($$)) {{ $ $((".do_not_click"".do_not_click").).clickclick((functionfunction()() {{ $ $((thisthis).).removeremove();(); }}););
$ $((documentdocument).).bindbind(("remove""remove",, functionfunction((ee)) {{ alertalert(( "uuh ooh!""uuh ooh!" );); }}););}}););
Example: Override a MethodExample: Override a MethodExample: Override a MethodExample: Override a MethodExample: Override a Method
$ $((".do_not_click"".do_not_click").).clickclick((functionfunction()() {{ $ $subsub((thisthis).).removeremove();(); }}););
$ $((documentdocument).).bindbind(("remove""remove",, functionfunction((ee)) {{ alertalert(( "uuh ooh!""uuh ooh!" );); }}););
Partial IsolationPartial IsolationPartial IsolationPartial IsolationPartial Isolation
mmeetthhooddssmmeetthhooddssmmeetthhooddssmmeetthhooddssmmeetthhooddss - still point to original jQuery - still point to original jQuery - still point to original jQuery - still point to original jQuery - still point to original jQuery
eevveennttsseevveennttsseevveennttsseevveennttsseevveennttss - will still be through main jQuery - will still be through main jQuery - will still be through main jQuery - will still be through main jQuery - will still be through main jQuery
ddaattaaddaattaaddaattaaddaattaaddaattaa - is bound to elements through main jQuery - is bound to elements through main jQuery - is bound to elements through main jQuery - is bound to elements through main jQuery - is bound to elements through main jQuery
AAjjaaxxAAjjaaxxAAjjaaxxAAjjaaxxAAjjaaxx - runs through the main jQuery - runs through the main jQuery - runs through the main jQuery - runs through the main jQuery - runs through the main jQuery
...............
Example: Plugin-Specific MethodsExample: Plugin-Specific MethodsExample: Plugin-Specific MethodsExample: Plugin-Specific MethodsExample: Plugin-Specific Methods
((functionfunction()() {{ // copy jQuery using sub()// copy jQuery using sub() varvar plugin plugin == jQuery jQuery..subsub();();
// extend copy with new methods// extend copy with new methods plugin plugin..fnfn..extendextend(({{ … … }}););
// add to original jQuery// add to original jQuery jQuery jQuery..fnfn..myplugin myplugin == functionfunction()() {{ // return our special plugin version// return our special plugin version returnreturn pluginplugin(( thisthis );); }};;}})();)();
Example: Plugin-Specific MethodsExample: Plugin-Specific MethodsExample: Plugin-Specific MethodsExample: Plugin-Specific MethodsExample: Plugin-Specific Methods
pluginplugin..fnfn..extendextend(({{ open open:: functionfunction()() {{ returnreturn thisthis..showshow();(); }},, close close:: functionfunction()() {{ returnreturn thisthis..hidehide();(); }}}}););
jQueryjQuery..fnfn..myplugin myplugin == functionfunction()() {{ thisthis..addClassaddClass(("plugin""plugin");); returnreturn pluginplugin(( thisthis ););}};;
Example: Plugin-Specific MethodsExample: Plugin-Specific MethodsExample: Plugin-Specific MethodsExample: Plugin-Specific MethodsExample: Plugin-Specific Methods
$$((documentdocument).).readyready((functionfunction()() {{ $ $(('#main''#main').).openopen();(); // does not work!// does not work!}}););
Example: Plugin-Specific MethodsExample: Plugin-Specific MethodsExample: Plugin-Specific MethodsExample: Plugin-Specific MethodsExample: Plugin-Specific Methods
$$((documentdocument).).readyready((functionfunction()() {{ // call plugin// call plugin // open method now exists// open method now exists $ $(('#main''#main').).mypluginmyplugin().().openopen();();}}););
That's it!That's it!That's it!That's it!That's it!1.5.1 RC1 out now1.5.1 RC1 out now1.5.1 RC1 out now1.5.1 RC1 out now1.5.1 RC1 out now
1.5.1: February 24th1.5.1: February 24th1.5.1: February 24th1.5.1: February 24th1.5.1: February 24th
Any Questions?Any Questions?Any Questions?Any Questions?Any Questions?Martin KleppeMartin KleppeMartin KleppeMartin KleppeMartin Kleppe@aemkei@aemkei@aemkei@aemkei@aemkei