SlideShare une entreprise Scribd logo
1  sur  28
Télécharger pour lire hors ligne
Bastian Feder | Liip Ag


jQuery secrets
jQuery secrets
Bastian Feder       IPC Spring 2011 Berlin
lapistano@php.net           31th May 2011
Me, myself & I

 JavaScript since 2002
 PHP since 2001
 Opensource addict
   PHP manual translations
   FluentDOM
Utilities
Saving the state

 jQuery.data(element, key[, value])
   Store any kind of information
   on a DOM element
   Circular references avoided
   Low level function use
   $().data() instead.
Saving possible?

 jQuery.acceptData( element )
   Low level function invoked by
   $(elem).data()
   Extend jQuery.noData to set
   additional constraints
   Does not raise an
   error/exception
Removing the state

 jQuery.removeData(element[, key])
   Low level function use
   $().removeData([key])
   instead.
   Removes all data if no key is
   passed.
State example

 var logo = $('#jq-siteLogo');

 $(document).data('logo', logo);

 $(logo).detach();

 $('fieldset[class="toc"]')
   .before($(document).data('logo'));

 $(document).removeData('logo');
Extending for the good

  jQuery.extend([deep], target[, object1][, objectN])

var defaults = {
    validate: false,
    limit: {max: 5, min: 1},
    name: "foo"
};
var options = {
    validate: true,
    limit: {max:10}
};
var settings = $.extend(true, {}, defaults, options);
Extending for the good                        (II)

(function($, jQuery, undefined) {

 jQuery.fn.myPlugin = function( options ) {
   var options = $.extend(
      {},
      jQuery.fn.myPlugin.defaults,
      Options
   );
   // put plugin code here //
 }

 jQuery.fn.myPlugin.defaults = {
    'color': '#fff',
    'myPublicMethod': function(){}
 };

})(jQuery, jQuery);
jQuery.props[]

 Register of translations
 Used by .attr()
  jQuery.props = {
     "for"         : "htmlFor",
     "class"       : "className",
     "frameborder" : "frameBorder",
     …
  };

  jQuery.props['uiwDiv'] =
      'ui-jeopardysection-gameboard-header';
AJAX
Global AJAX settings

  jQuery.ajaxSetup( options )

$.ajaxSetup({
   url: "/xmlhttp/",
   username: "paul",
   passwort: "secret"

});
$.ajax({ data: myData });
Global AJAX settings                (II)


 Methods to set properties defined by $.ajax()
 Examples:
   $.ajaxSuccess()
   $.ajaxError()
   $.ajaxStart()
   …
Shortcuts

  .load(url,[data,]
     [complete(responseText, textStatus, XHR)])

$('#ticker').load('http://liip.ch#entry1790');
Promises & Deferreds

  Proposed by CommonJS
  Since jQuery 1.5

var a1 = $.ajax('page1');
var a2 = $.ajax('page2');

$.when(a1, a2).then(
  function() { alert('Called when request successful!'),
  function() { alert('Called, when request failed.')
}
Events
Event binding

  .bind(type[, data], handler(event))
    'type' might also be an object

$('.clickable').bind({
  'click': function(event) { //callback },
  'mousedown': function(event) { //callback }
});
Namespaces

$('.clickable').bind('click.namespace', function(e){});

$('.clickable').bind({
  'click.namespace': function(event) { //callback },
  'mousedown.namespace': function(event) { //callback }
});

$('.clickable').unbind('.namespace');
„global“ Events

  ajaxStart
  ajaxStop

$('#indicator')
  .bind({
    'ajaxStart.ajaxindicator': function() {
       // show tumble image
    },
    'ajaxStop.ajaxindicator': function() {
       // hide tumble image
    }
});
Selfdefined speeding

$.extend(jQuery.fx.speeds, {
   slow: 600,
   fast: 200,
   // Default speed
   _default: 400
},
{
   slowmotion: 100,
});

$('#clickme').click(function() {
  $('#book').fadeIn('slowmotion');
});
Extending
 jQuery
jQuery plugins

  jQuery.error( msg )

jQuery.error = function( msg, code ) {
  var error = [];
  error[msg] = message;
  error['code'] = $errorcode;
  if (typeof console != undefined) {
    console.error(error)
  }
  throw msg;
}
jQuery UI

$.extend('ui.autosuggest.prototype, {
  _search: function( value ) {
    // always save the actual value,
    // not the one passed as an argument
    this.term = this.element
      .addClass( "ui-autocomplete-loading"
      .val();

      this.source( { term: value }, this.response );
});
Sizzle.selectors

  jQuery.expr.filters
  jQuery.expr[':']

 $.extend(
   $.expr.filters,
   {
     "myPseudoSelector": function( node, index, match ) {
       // return true, if s.th. Was selected
       // return false, if not.
     }
   });
Book recommendation

             Jakob Westhoff
             http://westhoffswelt.de
             ISBN:
             978-3-86802-052-6
             E-Book-ISBN:
             978-3-86802-237-7
Feedback, pls

 Joind.in
 http://joind.in/talk/view/3511
 Slides
 http://slideshare.net/lapistano
 Email
 lapstano@php.net
 IRC on freenode
 lapistano
License

 This set of slides and the source code included
  in the download package is licensed under the

 Creative Commons Attribution-
 Noncommercial-Share Alike 2.0 Generic
 License


 http://creativecommons.org/licenses/by-nc-sa/2.0/deed.en

Contenu connexe

Tendances

Design Patterns in PHP5
Design Patterns in PHP5 Design Patterns in PHP5
Design Patterns in PHP5
Wildan Maulana
 
Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2
Fabien Potencier
 
Doctrine fixtures
Doctrine fixturesDoctrine fixtures
Doctrine fixtures
Bill Chang
 
Dependency Injection IPC 201
Dependency Injection IPC 201Dependency Injection IPC 201
Dependency Injection IPC 201
Fabien Potencier
 

Tendances (19)

The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
 
The Origin of Lithium
The Origin of LithiumThe Origin of Lithium
The Origin of Lithium
 
Lithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate FrameworksLithium: The Framework for People Who Hate Frameworks
Lithium: The Framework for People Who Hate Frameworks
 
Quebec pdo
Quebec pdoQuebec pdo
Quebec pdo
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
Design Patterns in PHP5
Design Patterns in PHP5 Design Patterns in PHP5
Design Patterns in PHP5
 
Decoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DICDecoupling with Design Patterns and Symfony2 DIC
Decoupling with Design Patterns and Symfony2 DIC
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 
PhpUnit - The most unknown Parts
PhpUnit - The most unknown PartsPhpUnit - The most unknown Parts
PhpUnit - The most unknown Parts
 
Unittests für Dummies
Unittests für DummiesUnittests für Dummies
Unittests für Dummies
 
Design how your objects talk through mocking
Design how your objects talk through mockingDesign how your objects talk through mocking
Design how your objects talk through mocking
 
Silex meets SOAP & REST
Silex meets SOAP & RESTSilex meets SOAP & REST
Silex meets SOAP & REST
 
Crafting beautiful software
Crafting beautiful softwareCrafting beautiful software
Crafting beautiful software
 
Mocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnitMocking Dependencies in PHPUnit
Mocking Dependencies in PHPUnit
 
Php unit the-mostunknownparts
Php unit the-mostunknownpartsPhp unit the-mostunknownparts
Php unit the-mostunknownparts
 
Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2Unit and Functional Testing with Symfony2
Unit and Functional Testing with Symfony2
 
Doctrine fixtures
Doctrine fixturesDoctrine fixtures
Doctrine fixtures
 
Dependency Injection IPC 201
Dependency Injection IPC 201Dependency Injection IPC 201
Dependency Injection IPC 201
 
Mocking Demystified
Mocking DemystifiedMocking Demystified
Mocking Demystified
 

En vedette

international PHP2011_Kore Nordmann_Designing multilingual applications
international PHP2011_Kore Nordmann_Designing multilingual applications international PHP2011_Kore Nordmann_Designing multilingual applications
international PHP2011_Kore Nordmann_Designing multilingual applications
smueller_sandsmedia
 
international PHP2011_Jordi Boggiano_PHP Reset
international PHP2011_Jordi Boggiano_PHP Resetinternational PHP2011_Jordi Boggiano_PHP Reset
international PHP2011_Jordi Boggiano_PHP Reset
smueller_sandsmedia
 
international PHP2011_ilia alshanetsky_Hidden Features of PHP
international PHP2011_ilia alshanetsky_Hidden Features of PHPinternational PHP2011_ilia alshanetsky_Hidden Features of PHP
international PHP2011_ilia alshanetsky_Hidden Features of PHP
smueller_sandsmedia
 
webinale2011_Dirk Jesse:Responsive Web Design oder "Unwissenheit ist ein Segen"
webinale2011_Dirk Jesse:Responsive Web Design oder "Unwissenheit ist ein Segen"webinale2011_Dirk Jesse:Responsive Web Design oder "Unwissenheit ist ein Segen"
webinale2011_Dirk Jesse:Responsive Web Design oder "Unwissenheit ist ein Segen"
smueller_sandsmedia
 
international PHP2011_Bastian Hofmann_Mashing up java script
international PHP2011_Bastian Hofmann_Mashing up java scriptinternational PHP2011_Bastian Hofmann_Mashing up java script
international PHP2011_Bastian Hofmann_Mashing up java script
smueller_sandsmedia
 
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitinternational PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
smueller_sandsmedia
 
webinale2011_Kai Radusch_Landingpage-Optimierung für Adwords-Kampagnen
webinale2011_Kai Radusch_Landingpage-Optimierung für Adwords-Kampagnenwebinale2011_Kai Radusch_Landingpage-Optimierung für Adwords-Kampagnen
webinale2011_Kai Radusch_Landingpage-Optimierung für Adwords-Kampagnen
smueller_sandsmedia
 

En vedette (8)

international PHP2011_Kore Nordmann_Designing multilingual applications
international PHP2011_Kore Nordmann_Designing multilingual applications international PHP2011_Kore Nordmann_Designing multilingual applications
international PHP2011_Kore Nordmann_Designing multilingual applications
 
international PHP2011_Jordi Boggiano_PHP Reset
international PHP2011_Jordi Boggiano_PHP Resetinternational PHP2011_Jordi Boggiano_PHP Reset
international PHP2011_Jordi Boggiano_PHP Reset
 
Golf
GolfGolf
Golf
 
international PHP2011_ilia alshanetsky_Hidden Features of PHP
international PHP2011_ilia alshanetsky_Hidden Features of PHPinternational PHP2011_ilia alshanetsky_Hidden Features of PHP
international PHP2011_ilia alshanetsky_Hidden Features of PHP
 
webinale2011_Dirk Jesse:Responsive Web Design oder "Unwissenheit ist ein Segen"
webinale2011_Dirk Jesse:Responsive Web Design oder "Unwissenheit ist ein Segen"webinale2011_Dirk Jesse:Responsive Web Design oder "Unwissenheit ist ein Segen"
webinale2011_Dirk Jesse:Responsive Web Design oder "Unwissenheit ist ein Segen"
 
international PHP2011_Bastian Hofmann_Mashing up java script
international PHP2011_Bastian Hofmann_Mashing up java scriptinternational PHP2011_Bastian Hofmann_Mashing up java script
international PHP2011_Bastian Hofmann_Mashing up java script
 
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnitinternational PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
international PHP2011_Bastian Feder_The most unknown Parts of PHPUnit
 
webinale2011_Kai Radusch_Landingpage-Optimierung für Adwords-Kampagnen
webinale2011_Kai Radusch_Landingpage-Optimierung für Adwords-Kampagnenwebinale2011_Kai Radusch_Landingpage-Optimierung für Adwords-Kampagnen
webinale2011_Kai Radusch_Landingpage-Optimierung für Adwords-Kampagnen
 

Similaire à international PHP2011_Bastian Feder_jQuery's Secrets

Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
Luke Summerfield
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
Jarod Ferguson
 

Similaire à international PHP2011_Bastian Feder_jQuery's Secrets (20)

jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
jQuery's Secrets
jQuery's SecretsjQuery's Secrets
jQuery's Secrets
 
J query training
J query trainingJ query training
J query training
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
 
jQuery: Events, Animation, Ajax
jQuery: Events, Animation, AjaxjQuery: Events, Animation, Ajax
jQuery: Events, Animation, Ajax
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery Applications
 
jQuery
jQueryjQuery
jQuery
 
Clean Javascript
Clean JavascriptClean Javascript
Clean Javascript
 
jQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and PerformancejQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and Performance
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
 
Hooks WCSD12
Hooks WCSD12Hooks WCSD12
Hooks WCSD12
 
jQuery, CSS3 and ColdFusion
jQuery, CSS3 and ColdFusionjQuery, CSS3 and ColdFusion
jQuery, CSS3 and ColdFusion
 
WordPress Realtime - WordCamp São Paulo 2015
WordPress Realtime - WordCamp São Paulo 2015WordPress Realtime - WordCamp São Paulo 2015
WordPress Realtime - WordCamp São Paulo 2015
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
 
jQuery
jQueryjQuery
jQuery
 
Jquery optimization-tips
Jquery optimization-tipsJquery optimization-tips
Jquery optimization-tips
 
JQuery introduction
JQuery introductionJQuery introduction
JQuery introduction
 
Javascript - Beyond-jQuery
Javascript - Beyond-jQueryJavascript - Beyond-jQuery
Javascript - Beyond-jQuery
 
Separation of concerns - DPC12
Separation of concerns - DPC12Separation of concerns - DPC12
Separation of concerns - DPC12
 

Plus de smueller_sandsmedia

webinale 2011_Gabriel Yoran_Der Schlüssel zum erfolg: Besser aussehen, als ma...
webinale 2011_Gabriel Yoran_Der Schlüssel zum erfolg: Besser aussehen, als ma...webinale 2011_Gabriel Yoran_Der Schlüssel zum erfolg: Besser aussehen, als ma...
webinale 2011_Gabriel Yoran_Der Schlüssel zum erfolg: Besser aussehen, als ma...
smueller_sandsmedia
 
international PHP2011_Henning Wolf_ Mit Retrospektivenzu erfolgreichen Projekten
international PHP2011_Henning Wolf_ Mit Retrospektivenzu erfolgreichen Projekteninternational PHP2011_Henning Wolf_ Mit Retrospektivenzu erfolgreichen Projekten
international PHP2011_Henning Wolf_ Mit Retrospektivenzu erfolgreichen Projekten
smueller_sandsmedia
 
international PHP2011_Kore Nordmann_Tobias Schlitt_Modular Application Archit...
international PHP2011_Kore Nordmann_Tobias Schlitt_Modular Application Archit...international PHP2011_Kore Nordmann_Tobias Schlitt_Modular Application Archit...
international PHP2011_Kore Nordmann_Tobias Schlitt_Modular Application Archit...
smueller_sandsmedia
 
webinale2011_Chris Mills_Brave new world of HTML5Html5
webinale2011_Chris Mills_Brave new world of HTML5Html5webinale2011_Chris Mills_Brave new world of HTML5Html5
webinale2011_Chris Mills_Brave new world of HTML5Html5
smueller_sandsmedia
 
international PHP2011_J.Hartmann_DevOps für PHP
international PHP2011_J.Hartmann_DevOps für PHPinternational PHP2011_J.Hartmann_DevOps für PHP
international PHP2011_J.Hartmann_DevOps für PHP
smueller_sandsmedia
 
webinale2011_Daniel Höpfner_Förderprogramme für dummies
webinale2011_Daniel Höpfner_Förderprogramme für dummieswebinale2011_Daniel Höpfner_Förderprogramme für dummies
webinale2011_Daniel Höpfner_Förderprogramme für dummies
smueller_sandsmedia
 

Plus de smueller_sandsmedia (6)

webinale 2011_Gabriel Yoran_Der Schlüssel zum erfolg: Besser aussehen, als ma...
webinale 2011_Gabriel Yoran_Der Schlüssel zum erfolg: Besser aussehen, als ma...webinale 2011_Gabriel Yoran_Der Schlüssel zum erfolg: Besser aussehen, als ma...
webinale 2011_Gabriel Yoran_Der Schlüssel zum erfolg: Besser aussehen, als ma...
 
international PHP2011_Henning Wolf_ Mit Retrospektivenzu erfolgreichen Projekten
international PHP2011_Henning Wolf_ Mit Retrospektivenzu erfolgreichen Projekteninternational PHP2011_Henning Wolf_ Mit Retrospektivenzu erfolgreichen Projekten
international PHP2011_Henning Wolf_ Mit Retrospektivenzu erfolgreichen Projekten
 
international PHP2011_Kore Nordmann_Tobias Schlitt_Modular Application Archit...
international PHP2011_Kore Nordmann_Tobias Schlitt_Modular Application Archit...international PHP2011_Kore Nordmann_Tobias Schlitt_Modular Application Archit...
international PHP2011_Kore Nordmann_Tobias Schlitt_Modular Application Archit...
 
webinale2011_Chris Mills_Brave new world of HTML5Html5
webinale2011_Chris Mills_Brave new world of HTML5Html5webinale2011_Chris Mills_Brave new world of HTML5Html5
webinale2011_Chris Mills_Brave new world of HTML5Html5
 
international PHP2011_J.Hartmann_DevOps für PHP
international PHP2011_J.Hartmann_DevOps für PHPinternational PHP2011_J.Hartmann_DevOps für PHP
international PHP2011_J.Hartmann_DevOps für PHP
 
webinale2011_Daniel Höpfner_Förderprogramme für dummies
webinale2011_Daniel Höpfner_Förderprogramme für dummieswebinale2011_Daniel Höpfner_Förderprogramme für dummies
webinale2011_Daniel Höpfner_Förderprogramme für dummies
 

Dernier

Dernier (20)

Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 

international PHP2011_Bastian Feder_jQuery's Secrets

  • 1. Bastian Feder | Liip Ag jQuery secrets
  • 2. jQuery secrets Bastian Feder IPC Spring 2011 Berlin lapistano@php.net 31th May 2011
  • 3. Me, myself & I JavaScript since 2002 PHP since 2001 Opensource addict PHP manual translations FluentDOM
  • 5. Saving the state jQuery.data(element, key[, value]) Store any kind of information on a DOM element Circular references avoided Low level function use $().data() instead.
  • 6. Saving possible? jQuery.acceptData( element ) Low level function invoked by $(elem).data() Extend jQuery.noData to set additional constraints Does not raise an error/exception
  • 7. Removing the state jQuery.removeData(element[, key]) Low level function use $().removeData([key]) instead. Removes all data if no key is passed.
  • 8. State example var logo = $('#jq-siteLogo'); $(document).data('logo', logo); $(logo).detach(); $('fieldset[class="toc"]') .before($(document).data('logo')); $(document).removeData('logo');
  • 9. Extending for the good jQuery.extend([deep], target[, object1][, objectN]) var defaults = { validate: false, limit: {max: 5, min: 1}, name: "foo" }; var options = { validate: true, limit: {max:10} }; var settings = $.extend(true, {}, defaults, options);
  • 10. Extending for the good (II) (function($, jQuery, undefined) { jQuery.fn.myPlugin = function( options ) { var options = $.extend( {}, jQuery.fn.myPlugin.defaults, Options ); // put plugin code here // } jQuery.fn.myPlugin.defaults = { 'color': '#fff', 'myPublicMethod': function(){} }; })(jQuery, jQuery);
  • 11. jQuery.props[] Register of translations Used by .attr() jQuery.props = { "for" : "htmlFor", "class" : "className", "frameborder" : "frameBorder", … }; jQuery.props['uiwDiv'] = 'ui-jeopardysection-gameboard-header';
  • 12. AJAX
  • 13. Global AJAX settings jQuery.ajaxSetup( options ) $.ajaxSetup({ url: "/xmlhttp/", username: "paul", passwort: "secret" }); $.ajax({ data: myData });
  • 14. Global AJAX settings (II) Methods to set properties defined by $.ajax() Examples: $.ajaxSuccess() $.ajaxError() $.ajaxStart() …
  • 15. Shortcuts .load(url,[data,] [complete(responseText, textStatus, XHR)]) $('#ticker').load('http://liip.ch#entry1790');
  • 16. Promises & Deferreds Proposed by CommonJS Since jQuery 1.5 var a1 = $.ajax('page1'); var a2 = $.ajax('page2'); $.when(a1, a2).then( function() { alert('Called when request successful!'), function() { alert('Called, when request failed.') }
  • 18. Event binding .bind(type[, data], handler(event)) 'type' might also be an object $('.clickable').bind({ 'click': function(event) { //callback }, 'mousedown': function(event) { //callback } });
  • 19. Namespaces $('.clickable').bind('click.namespace', function(e){}); $('.clickable').bind({ 'click.namespace': function(event) { //callback }, 'mousedown.namespace': function(event) { //callback } }); $('.clickable').unbind('.namespace');
  • 20. „global“ Events ajaxStart ajaxStop $('#indicator') .bind({ 'ajaxStart.ajaxindicator': function() { // show tumble image }, 'ajaxStop.ajaxindicator': function() { // hide tumble image } });
  • 21. Selfdefined speeding $.extend(jQuery.fx.speeds, { slow: 600, fast: 200, // Default speed _default: 400 }, { slowmotion: 100, }); $('#clickme').click(function() { $('#book').fadeIn('slowmotion'); });
  • 23. jQuery plugins jQuery.error( msg ) jQuery.error = function( msg, code ) { var error = []; error[msg] = message; error['code'] = $errorcode; if (typeof console != undefined) { console.error(error) } throw msg; }
  • 24. jQuery UI $.extend('ui.autosuggest.prototype, { _search: function( value ) { // always save the actual value, // not the one passed as an argument this.term = this.element .addClass( "ui-autocomplete-loading" .val(); this.source( { term: value }, this.response ); });
  • 25. Sizzle.selectors jQuery.expr.filters jQuery.expr[':'] $.extend( $.expr.filters, { "myPseudoSelector": function( node, index, match ) { // return true, if s.th. Was selected // return false, if not. } });
  • 26. Book recommendation Jakob Westhoff http://westhoffswelt.de ISBN: 978-3-86802-052-6 E-Book-ISBN: 978-3-86802-237-7
  • 27. Feedback, pls Joind.in http://joind.in/talk/view/3511 Slides http://slideshare.net/lapistano Email lapstano@php.net IRC on freenode lapistano
  • 28. License This set of slides and the source code included in the download package is licensed under the Creative Commons Attribution- Noncommercial-Share Alike 2.0 Generic License http://creativecommons.org/licenses/by-nc-sa/2.0/deed.en