Dispatching Custom Events for Front End Analytics Application

When we have a web analytics application that collects front end event data such as Tealium, Adobe Analytics and so on, we can dispatch an custom event whenever user does action on the page. For example, we can dispatch a custom event to indicate the user clicked certain button on the page.

Event can be emitted from the custom object that is exposed globally.

Then, the analytics application can listen to the event and do something like this.

mysite.events.on('widget:opened', function() { 
  // Whatever the analytics function provided by the vendor
  whatever.function.sendData('widget:opened');
});

The easiest way to do this is to use node.js events. For example, we have a global namespace called mysite. We can add events object that is the EventEmitter.

Then, we can simply emit event when the element is clicked. This works on most browsers including IE11.

import { EventEmitter } from 'events';
mysite.events = new EventEmitter();

document.targetElem.addEventListener('click', () => {
  mysite.events.emit('widget:opened');
})

Because events are from node.js, you may need to use plugins in the bundler to use the module. For example, if you are using rollup, you need to use rollup-plugin-node-builtins.

The alternative is to dispatch a custom event. It is not as clean as emitting event, but it also works.

const widgetOpenEvent = new CustomEvent('widget:opened')
document.targetElem.addEventListener('click', () => {
  document.dispatchEvent(widgetOpenEvent);
});

Then, analytics code can attach an event listener to the document to listen to this custom event. Note that CutomEvent requires a polyfill if you need to make it work with IE11.

Front-End
TypeScript: type aliases to check type equality

This post is to analyse how the type equality check by using type aliases proposed by Matt Pocock in his twitter post. These type aliases allow us to elegantly express type equality checks in unit tests. All we need to do is to pass the output and expected types in …

Front-End
Fixing it.only type error in Jest

If you are getting a type error with it.only in Jest, it could be due to incorrect TypeScript typings or incompatible versions of Jest and TypeScript. To resolve this issue, you can try the following steps: Make sure you have the latest versions of Jest and its TypeScript typings installed …

Front-End
yup conditional validation example

Here’s an example of a Yup validation logic where the first input field is optional but, if filled, it must contain only alphabetic characters, and the second input field is required: import * as Yup from “yup”; const validationSchema = Yup.object().shape({ firstField: Yup.string().matches(/^[A-Za-z]*$/, { message: “First field must contain only …