SlideShare ist ein Scribd-Unternehmen logo
1 von 80
Downloaden Sie, um offline zu lesen
How
CUSTOM EVENTS
 will save the universe
Law of Demeter
“Each unit should have
only limited knowledge
  about other units.”
(we break this rule
   all the time)
the Law of Demeter is about removing
unnecessary coupling
custom events can help
  decouple your code
Broadcaster and receiver
   don’t have to know
  about one another…
… so there’s far less to mock
      in your unit tests
YOU DO HAVE
UNIT TESTS, RIGHT?
How do custom events work?
$(document).observe('custom:event', function(event) {
  var customData = event.memo;
  // stuff
});
$('troz').fire('custom:event', { foo: "bar" });
$(document).bind('customevent', function(event, customData) {
  // stuff
});
$('#troz').trigger('customevent', [{ foo: "bar" }]);
$(document).addEvent('customevent', function(event, customData) {
  // stuff
});
$('troz').fireEvent('customevent', { foo: "bar" });
BUT WHY?
Why?




       Makes testing easier
        (maybe you’ll do it now)
Why?




       Rapid prototyping
Why?




       More versatile than callbacks
Why?




       Can be bubbled/canceled
Why?




       Can handle exceptions properly
                  (in theory)
(quoth Dean Edwards)
In Prototype,
exceptions raised in one handler
  won’t affect another handler
(is this a big deal? smart people disagree)
CASE
STUDIES
Case Studies




               #
                   1
Case Studies




               (script.aculo.us 2.0)
scripty2 uses custom events…




                …as a “metronome” for effects
window.setTimeout(function() {
  document.fire('effect:heartbeat');
}, 0);
document.observe('effect:heartbeat', advanceEffectByOneFrame);
Seems pointless…
 …until you need to debug
Step through an animation
                         frame by frame

document.observe('keydown', function(event) {
  if (event.keyCode === Event.KEY_RIGHT) {
    document.fire('effect:heartbeat');
  }
});
scripty2 uses custom events…




                         …to pass messages
                        between UI widgets
S2.UI.Menu
(used by other S2.UI components)
var menu = new S2.UI.Menu();
menu.addChoice("Foo");
menu.addChoice("Bar");
someElement.insert(menu);
menu.open();
S2.UI widgets act like elements when needed, so...




    menu.observe('ui:menu:selected', function(event) {
      console.log('user clicked on:', event.memo.element);
    });
Easy to use
in any context
Button with menu
ASIDE:
Custom events are cancelable
var event = $('troz').fire('custom:event');
if (!event.stopped) performSomeDefaultAction();
(prevent all menus from appearing)




    document.observe('ui:menu:before:open', function(event) {
      event.stop();
    });
scripty2 uses custom events…




                    …as hooks for debugging
“Why aren’t these
 effects queueing
  like I expect?”
document.observe('effect:dequeued', function(event) {
  var queue = event.memo;
  console.log("Effects in queue:", queue.size());
});
You get debugging
   FOR FREE
Case Studies




               #
                   2
Case Studies




               Mouse wheel
http://adomas.org/javascript-mouse-wheel/




window.addEventListener('DOMMouseScroll', handler);
window.onmousewheel = handler;

function handler(event) {
  var delta;
  if (event.wheelDelta) {
    delta = event.wheelDelta / 120;
    if (window.opera) delta = -delta; // (not a joke)
  } else if (event.detail) {
    delta = -event.detail / 3;
  }

    // Do stuff with your stupid delta
}
Instead, do this:
window.addEventListener('DOMMouseScroll', handler);
window.onmousewheel = handler;

function handler(event) {
  var delta;
  if (event.wheelDelta) {
    delta = event.wheelDelta / 120;
    if (window.opera) delta = -delta; // (not a joke)
  } else if (event.detail) {
    delta = -event.detail / 3;
  }

    // Fire a custom event with the normalized delta.
    var result = event.target.fire('mouse:wheel', { delta: delta });
    if (result.stopped) event.preventDefault();
}
See also:


hashchange
Case Studies




               #
                   3
Case Studies




               User idle state
http://perfectionkills.com/detect-idle-state-with-custom-events/




                             credit: kangax

document.observe('state:idle', function() {
  turnOffBackgroundAjaxRequests();
});

document.observe('state:active', function() {
  turnOnBackgroundAjaxRequests();
});
Case Studies




               #
                   4
Case Studies




               Keyboard events
(function() {
  var KEYS = {};
  KEYS[Event.KEY_ESC]      =   "esc";
  KEYS[Event.KEY_UP]       =   "up";
  KEYS[Event.KEY_DOWN]     =   "down";
  KEYS[Event.KEY_LEFT]     =   "left";
  KEYS[Event.KEY_RIGHT]    =   "right";
  // ... and so on

  function handler(event) {
    if (event.keyCode && KEYS[event.keyCode]) {
      event.element().fire("key:" + KEYS[event.keyCode], event);
    }
  }

  document.observe("keydown", handler);
})();
Then you’d be able to do
                  something like this:
document.observe('key:left', function() { moveSlide(-1); });
document.observe('key:right', function() { moveSlide( 1); });
Case Studies




               #
                   5
Data broadcasting
Server-sent events are awesome…
     …but not universally supported
for browsers that support server-sent events

var eventSource = $('event_source');
eventSource.observe('server-sent-event-name', function(event) {
  document.fire('data:received', event.data);
});
for browsers that don’t

new Ajax.Request('/legacy/polling', {
  onComplete: function(request) {
    document.fire('data:received', request.responseJSON);
  }
});
observer works with either approach

$(document).observe('data:received', function(event) {
  doStuffWithYourData(event.memo);
});
…and your unit tests can fire dummy data

function testThatSomethingHappened() {
  document.fire('data:received', FIXTURE_DATA);
  assertSomething();
}
FAQ
FAQ




       “What if my events
      aren’t DOM-related?”
(meh)
Use the DOM anyway, I say
FAQ




      “Isn’t this overkill?”
Yes, sometimes
FAQ




      “Aren’t events slow?”
NO
Events aren’t slow;
they’re synchronous
Events are only
as slow as the handlers
   attached to them
If performance is a concern, defer
window.setTimeout(function() {
  document.fire('costly:custom:event');
}, 0);
QUESTIONS?
    Andrew Dupont
http://andrewdupont.net

Weitere ähnliche Inhalte

Kürzlich hochgeladen

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Kürzlich hochgeladen (20)

FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
"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 ...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
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
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 

Empfohlen

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
ThinkNow
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 

Empfohlen (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

How Custom Events Will Save the Universe