SlideShare une entreprise Scribd logo
1  sur  12
Télécharger pour lire hors ligne
jQuery Behaviours

  bind, live, livequery




   Richard Paul, Sep 2009
Unobstrusive Javascript

Clean separation of
   Data (HTML)
   Style (CSS)
   Behaviour (Javascript)
 ...
 <form id="myForm" onsubmit="doSomething()">
   ...
 </form>
 ...
 <script type="text/javascript">
   $('#myForm').submit(function() { /* do something */ });
 </script>
Javascript Events

In Javascript, events bubble up.
<body>
  <div>
    <button>A button</button>
  </div>
</body>

Clicking the button bubbles the event up (button > div > body)

However IE doesn't play nice with form events                  (select, change,
submit, reset) , they don't bubble (1).


http://www.quirksmode.org/js/events_order.html
(1) http://blogs.sun.com/greimer/entry/event_delegation_for_submit_change
Event Delegation

Event delegation is the practice of letting events bubble up to a
handling node.

$('table').click(function(event) {
                                            r1c1    r1c2   r1c3
  alert(event.target.innerHTML);
});
                                            r2c1    r2c2   r2c3




As the target always points to the element the event
happened on, clicking on any cell will result in its contents
being alerted.
Adding new rows

When adding new cells, no extra work is required.
Clicking a new row will bubble up to the table's click handler.

Demo

In practice you would want to check the element is of the
correct type/class etc.
Binding Mechanisms in jQuery

There are a number of ways of binding behaviour in jQuery


bind        $('form').bind('submit', function(){})

live        $('form').live('submit', function(){})

liveQuery   $('form').liveQuery('submit', function(){})



Commonly when using bind you would use the shortcut method:
$('form').submit(function(){})
Comparison Grid

                        Event
            Dynamic                IE6 Form Events   jQuery Core
                      Delegation



  bind        No         No             Yes             Yes




  live        Yes        Yes             No             Yes




liveQuery     Yes        No             Yes          No (plugin)
Facebox Use Case




Facebox uses jQuery's clone method to copy the required
content into its modal dialog.

Any behaviours initialised with bind aren't applied to the
facebox content.
Facebox with jQuery.live

Solution, use jQuery.live to apply behaviours using the event
delegation style.

$('form').live('submit', function() {
  // submit form via ajax
  return false;
});




                        Simple!
What about Internet Exploder?




Recall that IE doesn't bubble form events... like submit.

Using jQuery.live doesn't work for IE as the event doesn't
bubble so the handler is never invoked.

http://www.chigarden.com/2007/10/tutorial-making-the-ie-voodoo-doll/
liveQuery

We can't use jQuery.bind as the form is dynamically created (by
facebox's clone call).

Enter liveQuery

This plugin adds the handler directly to the form element.

No event delegation, and it works in IE6!

Demo

liveQuery uses some fancy tricks (async binding etc) to keep
your website performing.
Comments, queries, suggestions or theories?

Contenu connexe

Tendances

Yahoo presentation: JavaScript Events
Yahoo presentation: JavaScript EventsYahoo presentation: JavaScript Events
Yahoo presentation: JavaScript EventsPeter-Paul Koch
 
The Fine Art of JavaScript Event Handling
The Fine Art of JavaScript Event HandlingThe Fine Art of JavaScript Event Handling
The Fine Art of JavaScript Event HandlingYorick Phoenix
 
The Real Story Behind JavaScript Performance on Mobile... Because Science!
The Real Story Behind JavaScript Performance on Mobile... Because Science!The Real Story Behind JavaScript Performance on Mobile... Because Science!
The Real Story Behind JavaScript Performance on Mobile... Because Science!Ryan J. Salva
 
State, Life cycle, Methods & Events
State, Life cycle, Methods & Events State, Life cycle, Methods & Events
State, Life cycle, Methods & Events NodeXperts
 
Getting classy with ES6
Getting classy with ES6Getting classy with ES6
Getting classy with ES6Andy Sharman
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJSAnass90
 
[Osxdev]7.handoff
[Osxdev]7.handoff[Osxdev]7.handoff
[Osxdev]7.handoffNAVER D2
 
DHTML - Events & Buttons
DHTML - Events  & ButtonsDHTML - Events  & Buttons
DHTML - Events & ButtonsDeep Patel
 
Jquery introduce
Jquery introduceJquery introduce
Jquery introduceMajor Ye
 
DOT NET LAB PROGRAM PERIYAR UNIVERSITY
DOT NET LAB PROGRAM PERIYAR UNIVERSITY DOT NET LAB PROGRAM PERIYAR UNIVERSITY
DOT NET LAB PROGRAM PERIYAR UNIVERSITY GOKUL SREE
 
jQuery Has Coding Standards
jQuery Has Coding StandardsjQuery Has Coding Standards
jQuery Has Coding StandardsRJ Bruneel
 
User Switcher for Cascade Server
User Switcher for Cascade ServerUser Switcher for Cascade Server
User Switcher for Cascade Serverhannonhill
 
jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Foreverstephskardal
 

Tendances (20)

JavaScript Libraries
JavaScript LibrariesJavaScript Libraries
JavaScript Libraries
 
Events - Part 2
Events - Part 2Events - Part 2
Events - Part 2
 
Yahoo presentation: JavaScript Events
Yahoo presentation: JavaScript EventsYahoo presentation: JavaScript Events
Yahoo presentation: JavaScript Events
 
The Fine Art of JavaScript Event Handling
The Fine Art of JavaScript Event HandlingThe Fine Art of JavaScript Event Handling
The Fine Art of JavaScript Event Handling
 
The Real Story Behind JavaScript Performance on Mobile... Because Science!
The Real Story Behind JavaScript Performance on Mobile... Because Science!The Real Story Behind JavaScript Performance on Mobile... Because Science!
The Real Story Behind JavaScript Performance on Mobile... Because Science!
 
State, Life cycle, Methods & Events
State, Life cycle, Methods & Events State, Life cycle, Methods & Events
State, Life cycle, Methods & Events
 
Getting classy with ES6
Getting classy with ES6Getting classy with ES6
Getting classy with ES6
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
[Osxdev]7.handoff
[Osxdev]7.handoff[Osxdev]7.handoff
[Osxdev]7.handoff
 
FuncUnit
FuncUnitFuncUnit
FuncUnit
 
DHTML - Events & Buttons
DHTML - Events  & ButtonsDHTML - Events  & Buttons
DHTML - Events & Buttons
 
Jquery introduce
Jquery introduceJquery introduce
Jquery introduce
 
DOT NET LAB PROGRAM PERIYAR UNIVERSITY
DOT NET LAB PROGRAM PERIYAR UNIVERSITY DOT NET LAB PROGRAM PERIYAR UNIVERSITY
DOT NET LAB PROGRAM PERIYAR UNIVERSITY
 
Bobcat Exchange Program
Bobcat Exchange ProgramBobcat Exchange Program
Bobcat Exchange Program
 
jQuery Has Coding Standards
jQuery Has Coding StandardsjQuery Has Coding Standards
jQuery Has Coding Standards
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
User Switcher for Cascade Server
User Switcher for Cascade ServerUser Switcher for Cascade Server
User Switcher for Cascade Server
 
jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Forever
 
Geb qa fest2017
Geb qa fest2017Geb qa fest2017
Geb qa fest2017
 
Vue.js for beginners
Vue.js for beginnersVue.js for beginners
Vue.js for beginners
 

Similaire à jQuery Behaviours

jQuery 1.7 Events
jQuery 1.7 EventsjQuery 1.7 Events
jQuery 1.7 Eventsdmethvin
 
Kick start with j query
Kick start with j queryKick start with j query
Kick start with j queryMd. Ziaul Haq
 
A to Z about JQuery - Become Newbie to Expert Java Developer
A to Z about JQuery - Become Newbie to Expert Java DeveloperA to Z about JQuery - Become Newbie to Expert Java Developer
A to Z about JQuery - Become Newbie to Expert Java DeveloperManoj Bhuva
 
QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...
QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...
QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...QAFest
 
JQUERY TUTORIALS
JQUERY TUTORIALSJQUERY TUTORIALS
JQUERY TUTORIALSMoize Roxas
 
J Query The Write Less Do More Javascript Library
J Query   The Write Less Do More Javascript LibraryJ Query   The Write Less Do More Javascript Library
J Query The Write Less Do More Javascript Libraryrsnarayanan
 
Will your code blend? : Toronto Code Camp 2010 : Barry Gervin
Will your code blend? : Toronto Code Camp 2010 : Barry GervinWill your code blend? : Toronto Code Camp 2010 : Barry Gervin
Will your code blend? : Toronto Code Camp 2010 : Barry GervinBarry Gervin
 
jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects  jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects WebStackAcademy
 
J Query (Complete Course) by Muhammad Ehtisham Siddiqui
J Query (Complete Course) by Muhammad Ehtisham SiddiquiJ Query (Complete Course) by Muhammad Ehtisham Siddiqui
J Query (Complete Course) by Muhammad Ehtisham SiddiquiMuhammad Ehtisham Siddiqui
 

Similaire à jQuery Behaviours (20)

Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
Lec 5
Lec 5Lec 5
Lec 5
 
Frontin like-a-backer
Frontin like-a-backerFrontin like-a-backer
Frontin like-a-backer
 
JQuery Overview
JQuery OverviewJQuery Overview
JQuery Overview
 
jQuery 1.7 Events
jQuery 1.7 EventsjQuery 1.7 Events
jQuery 1.7 Events
 
Unit3.pptx
Unit3.pptxUnit3.pptx
Unit3.pptx
 
Kick start with j query
Kick start with j queryKick start with j query
Kick start with j query
 
jQuery
jQueryjQuery
jQuery
 
A to Z about JQuery - Become Newbie to Expert Java Developer
A to Z about JQuery - Become Newbie to Expert Java DeveloperA to Z about JQuery - Become Newbie to Expert Java Developer
A to Z about JQuery - Become Newbie to Expert Java Developer
 
QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...
QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...
QA Fest 2017. Ярослав Святкин. Тестовый фреймворк GEB для тестирования WEB пр...
 
JQUERY TUTORIALS
JQUERY TUTORIALSJQUERY TUTORIALS
JQUERY TUTORIALS
 
J Query The Write Less Do More Javascript Library
J Query   The Write Less Do More Javascript LibraryJ Query   The Write Less Do More Javascript Library
J Query The Write Less Do More Javascript Library
 
Will your code blend? : Toronto Code Camp 2010 : Barry Gervin
Will your code blend? : Toronto Code Camp 2010 : Barry GervinWill your code blend? : Toronto Code Camp 2010 : Barry Gervin
Will your code blend? : Toronto Code Camp 2010 : Barry Gervin
 
jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects  jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects
 
Client Web
Client WebClient Web
Client Web
 
Digesting jQuery
Digesting jQueryDigesting jQuery
Digesting jQuery
 
Jquery
JqueryJquery
Jquery
 
J Query (Complete Course) by Muhammad Ehtisham Siddiqui
J Query (Complete Course) by Muhammad Ehtisham SiddiquiJ Query (Complete Course) by Muhammad Ehtisham Siddiqui
J Query (Complete Course) by Muhammad Ehtisham Siddiqui
 
J query training
J query trainingJ query training
J query training
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery Fundamentals
 

Plus de Richard Paul

Cucumber on the JVM with Groovy
Cucumber on the JVM with GroovyCucumber on the JVM with Groovy
Cucumber on the JVM with GroovyRichard Paul
 
Acceptance testing with Geb
Acceptance testing with GebAcceptance testing with Geb
Acceptance testing with GebRichard Paul
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionRichard Paul
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVCRichard Paul
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing FundamentalsRichard Paul
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax BasicsRichard Paul
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with MockitoRichard Paul
 

Plus de Richard Paul (9)

Cucumber on the JVM with Groovy
Cucumber on the JVM with GroovyCucumber on the JVM with Groovy
Cucumber on the JVM with Groovy
 
Acceptance testing with Geb
Acceptance testing with GebAcceptance testing with Geb
Acceptance testing with Geb
 
Acceptance tests
Acceptance testsAcceptance tests
Acceptance tests
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency Injection
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing Fundamentals
 
Using Dojo
Using DojoUsing Dojo
Using Dojo
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 

Dernier

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 Subbuapidays
 
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)wesley chun
 
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.pptxRustici Software
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfOverkill Security
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelDeepika Singh
 
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...apidays
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
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 DevelopmentsTrustArc
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
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...Drew Madelung
 

Dernier (20)

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
 
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)
 
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
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
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...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
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
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
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...
 

jQuery Behaviours

  • 1. jQuery Behaviours bind, live, livequery Richard Paul, Sep 2009
  • 2. Unobstrusive Javascript Clean separation of Data (HTML) Style (CSS) Behaviour (Javascript) ... <form id="myForm" onsubmit="doSomething()"> ... </form> ... <script type="text/javascript"> $('#myForm').submit(function() { /* do something */ }); </script>
  • 3. Javascript Events In Javascript, events bubble up. <body> <div> <button>A button</button> </div> </body> Clicking the button bubbles the event up (button > div > body) However IE doesn't play nice with form events (select, change, submit, reset) , they don't bubble (1). http://www.quirksmode.org/js/events_order.html (1) http://blogs.sun.com/greimer/entry/event_delegation_for_submit_change
  • 4. Event Delegation Event delegation is the practice of letting events bubble up to a handling node. $('table').click(function(event) { r1c1 r1c2 r1c3 alert(event.target.innerHTML); }); r2c1 r2c2 r2c3 As the target always points to the element the event happened on, clicking on any cell will result in its contents being alerted.
  • 5. Adding new rows When adding new cells, no extra work is required. Clicking a new row will bubble up to the table's click handler. Demo In practice you would want to check the element is of the correct type/class etc.
  • 6. Binding Mechanisms in jQuery There are a number of ways of binding behaviour in jQuery bind $('form').bind('submit', function(){}) live $('form').live('submit', function(){}) liveQuery $('form').liveQuery('submit', function(){}) Commonly when using bind you would use the shortcut method: $('form').submit(function(){})
  • 7. Comparison Grid Event Dynamic IE6 Form Events jQuery Core Delegation bind No No Yes Yes live Yes Yes No Yes liveQuery Yes No Yes No (plugin)
  • 8. Facebox Use Case Facebox uses jQuery's clone method to copy the required content into its modal dialog. Any behaviours initialised with bind aren't applied to the facebox content.
  • 9. Facebox with jQuery.live Solution, use jQuery.live to apply behaviours using the event delegation style. $('form').live('submit', function() { // submit form via ajax return false; }); Simple!
  • 10. What about Internet Exploder? Recall that IE doesn't bubble form events... like submit. Using jQuery.live doesn't work for IE as the event doesn't bubble so the handler is never invoked. http://www.chigarden.com/2007/10/tutorial-making-the-ie-voodoo-doll/
  • 11. liveQuery We can't use jQuery.bind as the form is dynamically created (by facebox's clone call). Enter liveQuery This plugin adds the handler directly to the form element. No event delegation, and it works in IE6! Demo liveQuery uses some fancy tricks (async binding etc) to keep your website performing.