what's new in jquery 1.5

66
jQuery 1.5 jQuery 1.5 jQuery 1.5 jQuery 1.5 jQuery 1.5 Martin Kleppe @aemkei Martin Kleppe @aemkei Martin Kleppe @aemkei Martin Kleppe @aemkei Martin Kleppe @aemkei http://ubilabs.net http://ubilabs.net http://ubilabs.net http://ubilabs.net http://ubilabs.net

Upload: martin-kleppe

Post on 19-Jan-2015

3.810 views

Category:

Technology


1 download

DESCRIPTION

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

TRANSCRIPT

Page 1: What's new in jQuery 1.5

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

Page 2: What's new in jQuery 1.5

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

Page 3: What's new in jQuery 1.5

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

Page 4: What's new in jQuery 1.5

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

Page 5: What's new in jQuery 1.5

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

Page 6: What's new in jQuery 1.5

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

Page 7: What's new in jQuery 1.5
Page 8: What's new in jQuery 1.5
Page 9: What's new in jQuery 1.5
Page 10: What's new in jQuery 1.5

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

Page 11: What's new in jQuery 1.5

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

Page 12: What's new in jQuery 1.5

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

Page 13: What's new in jQuery 1.5

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

Page 14: What's new in jQuery 1.5

Old SchoolOld SchoolOld SchoolOld SchoolOld School

$$..ajaxajax(({{ url url:: "/example""/example" }},, {{ success success:: functionfunction()(){{ // horray!// horray! }}}}););

Page 15: What's new in jQuery 1.5

New SchoolNew SchoolNew SchoolNew SchoolNew School

$$..ajaxajax(({{ url url:: "/example""/example" }}).). successsuccess(( functionfunction()(){{ /* horray! *//* horray! */}} ););

Page 16: What's new in jQuery 1.5

New SchoolNew SchoolNew SchoolNew SchoolNew School

$$..ajaxajax(({{ url url:: "/example""/example" }}).). successsuccess(( functionfunction()(){{ /* horray! *//* horray! */}} ););

Page 17: What's new in jQuery 1.5

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 */ ););

Page 18: What's new in jQuery 1.5

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 */ ))

Page 19: What's new in jQuery 1.5

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););

Page 20: What's new in jQuery 1.5

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

Page 21: What's new in jQuery 1.5

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

Page 22: What's new in jQuery 1.5

$.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

Page 23: What's new in jQuery 1.5

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;; }} }}););

Page 24: What's new in jQuery 1.5

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;; }}}}););

Page 25: What's new in jQuery 1.5

Prefilter dataTypePrefilter dataTypePrefilter dataTypePrefilter dataTypePrefilter dataType

// prefilter to JSON and script requests// prefilter to JSON and script requests$$..ajaxPrefilterajaxPrefilter(( "json script""json script",, functionfunction()() {{ // ...// ...}}););

Page 26: What's new in jQuery 1.5

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

Page 27: What's new in jQuery 1.5

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

Page 28: What's new in jQuery 1.5

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;; }} }} }}}}););

Page 29: What's new in jQuery 1.5

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

Page 30: What's new in jQuery 1.5

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"}}););

Page 31: What's new in jQuery 1.5

"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;; }} }}}}););

Page 32: What's new in jQuery 1.5

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

Page 33: What's new in jQuery 1.5

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}}

Page 34: What's new in jQuery 1.5

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

Page 35: What's new in jQuery 1.5

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

Page 36: What's new in jQuery 1.5

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 */ }} }};; }}););

Page 37: What's new in jQuery 1.5

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))

Page 38: What's new in jQuery 1.5

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 */ }}););

Page 39: What's new in jQuery 1.5

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

Page 40: What's new in jQuery 1.5

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 */ ););

Page 41: What's new in jQuery 1.5

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

Page 42: What's new in jQuery 1.5

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

Page 43: What's new in jQuery 1.5

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();();}}

Page 44: What's new in jQuery 1.5

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();();}}

Page 45: What's new in jQuery 1.5

jQuery.Deferred ShorthandjQuery.Deferred ShorthandjQuery.Deferred ShorthandjQuery.Deferred ShorthandjQuery.Deferred Shorthand

returnreturn $ $..DeferredDeferred((functionfunction(( deferred deferred )) {{ // your async code// your async code }}).).promisepromise();();    

Page 46: What's new in jQuery 1.5

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();();}};;

Page 47: What's new in jQuery 1.5

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

Page 48: What's new in jQuery 1.5

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

Page 49: What's new in jQuery 1.5

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

Page 50: What's new in jQuery 1.5

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)

Page 51: What's new in jQuery 1.5

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()(){}{}););

Page 52: What's new in jQuery 1.5

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

Page 53: What's new in jQuery 1.5

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

Page 54: What's new in jQuery 1.5

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

Page 55: What's new in jQuery 1.5

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

Page 56: What's new in jQuery 1.5

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 ););}};;

Page 57: What's new in jQuery 1.5

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 }}););    

Page 58: What's new in jQuery 1.5

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!" );); }}););}}););

Page 59: What's new in jQuery 1.5

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!" );); }}););    

Page 60: What's new in jQuery 1.5

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

...............

Page 61: What's new in jQuery 1.5

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 );); }};;}})();)();

Page 62: What's new in jQuery 1.5

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 ););}};;

Page 63: What's new in jQuery 1.5

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!}}););

Page 64: What's new in jQuery 1.5

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();();}}););

Page 65: What's new in jQuery 1.5

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

Page 66: What's new in jQuery 1.5

Any Questions?Any Questions?Any Questions?Any Questions?Any Questions?Martin KleppeMartin KleppeMartin KleppeMartin KleppeMartin Kleppe@aemkei@aemkei@aemkei@aemkei@aemkei