Cancel JavaScript Event Listeners with AbortController

One of the new features that was added in Chrome 88 is the ability to pass an AbortController‘s signal into addEventListener.

const controller = new AbortController();
const { signal } = controller;

document.querySelector('…').addEventListener('foo', (e) => {
  // …
}, {signal});

By calling controller.abort();, you can remove the listener from the event target, just like when calling element.removeEventListener.

💁‍♂️ Did you know you can use the AbortController to abort promises? It was its first intended use case when it was introduced back in 2017.

~

An excellent use-case here is that you can cancel multiple Event Listeners at once using it, as shared by Jake Archibald:

In the example above there are two competing event listeners. Whenever one of them finishes controller.abort(); is called, thus also removing the other one. Cool!

~

🔥 Like what you see? Want to stay in the loop? Here's how:

Monitoring changes in a web application

javascript-logo-banner

Eric Bidelman has bundled lots of code snippets around change events that can get triggered in the browser:

Changes range from simple things like DOM mutations and catching client-side errors to more complex notifications like knowing when the user’s battery is about to run out. The thing that remains constant are the ways to deal with them: callbacks, promises, events.

Below are some of use cases that I came up with. By no means is the list exhaustive. They’re mostly examples for observing the structure of an app, its state, and the properties of the device it’s running on.

Great list imho! Here’s the snippet to listening for changes in network connectivity, for example:

// Online/offline events.
window.addEventListener('online', e => {
  console.assert(navigator.onLine)
});
window.addEventListener('offline', e => {
  console.assert(!navigator.onLine)
});

// Network Information API navigator.connection.addEventListener('change', e => {
  console.log(navigator.connection.type, navigator.connection.downlinkMax);
});

Observing your web app →

jquery.unevent.js

A jQuery/Zepto plugin I’ve been using a lot lately to debounce (= attach with delay) event handlers. To be applied on scroll events for example, as you don’t want one long single scroll to pull down the performance of your webpage by constantly triggering the attached handling function.

$(window).on('scroll', function(e) {
    // update stuff *after* the scroll
}, 250);

I prefer jquery.unevent.js over this jQuery#debounce() for example as jquery.unevent.js extends jquery#on() with a simple third timing parameter.

jquery.unevent.js (demo) →
jquery.unevent.js (source) →

Yes, I know: a repost. It’s just that good!

Événement — PHP Event Dispatcher

Événement is a very simple event dispatching library for PHP. It has the same design goals as Silex and Pimple, to empower the user while staying concise and simple.

Concise indeed. At the core it’s a tad above 50 lines of codes.

Listening for events:

$emitter->on('user.created', function (User $user) use ($logger) {
    $logger->log(sprintf("User '%s' was created.", $user->getLogin()));
});

Dispatching events:

$emitter->emit('user.created', array($user));

Événement →

Object.observe()

var beingWatched = {};

function whatHappened(change) {
    console.log(change.name + " was " + change.type + " and is now " + change.object[change.name]);
}

function somethingChanged(changes) {
    changes.forEach(whatHappened);
}

Object.observe(beingWatched, somethingChanged);
beingWatched.a = "foo"; // new
beingWatched.a = "bar"; // updated
beingWatched.a = "bar"; // no change
beingWatched.b = "amazing"; // new

Object.observe() lets you add a listener to any JavaScript object that gets called whenever that object, or its properties, change.

As mentioned before, Object.observe() is coming in ECMAScript 6 (and is already available in Chrome Canary)

Object.observe() Demo →
Respond to change with Object.observe() →

React: Event-driven, non-blocking I/O with PHP

Inspired upon Node.js:

<?php

require 'vendor/autoload.php';

$stack = new React\Espresso\Stack(function ($request, $response) {
    $response->writeHead(200, array('Content-Type' => 'text/plain'));
    $response->end('Hello World\n');
});

echo 'Server running at http://127.0.0.1:1337' . PHP_EOL;
$stack->listen(1337);

React →

on{X} – Automate your life

on{X} lets you control and extend the capabilities of your Android phone using a JavaScript API to remotely program it.

Kinda like ifttt but then based on actions that happen on your mobile: an SMS being received, a location being entered/left, a change in mode of transport (from car to walking), etc.

A recipe like Text my wife “I’m on my way” when I leave work would programmatically end up being:

// Initializing variables 
var friend = { name : "my wife",phoneNumber : "+1234567890" } ;
var messageText = "I'm on my way";
var action = "exit"; // leaving
var location = { name : "work",latitude : "40.771442",longitude : "-73.974295" } ;

// create a geo region for the trigger to take place at
var region = device.regions.createRegion({
    latitude: parseFloat(location.latitude, 10),
    longitude: parseFloat(location.longitude, 10),
    name: location.name,
    radius: 1000
});

// register a callback which sends a message when entering/exiting the region (depends on action)
region.on(action, function (){
    device.messaging.sendSms({
            to: friend.phoneNumber,
            body: messageText
        },
        function (err) {
            if (err) {
                console.error('Error sending text message: ' + JSON.stringify(err));
            }
        }
    );
});

// start monitoring the region
device.regions.startMonitoring(region);

All can be configured via the website. Really neat!

on{X} →

(via teusje)