JSFiddle - React, Tailwind, and code Playground

by Leo Gallucci

HTML

<ul class="items"></ul>
<button class="add-item">Add item</button>
<div class="log"></div>

JavaScript

/////////////////////////////////////////////////////////////
// Creating a custom event listener on the document object //
/////////////////////////////////////////////////////////////
var $doc = $(document);
var $items = $('.items');
var $log = $('.log');

// DOM-related logic
$doc.on('addItem', function (event, value) {
    $items.append('<li>New item ' + value + '</li>')
});

// Business-related logic
$doc.on('addItem', function (event, value) {
    $log.html('<p>updating backend for item ' + value + '...</p>');
    //$.ajax({ ...etc... });
});

// Event-related logic
$('.add-item').on('click', function (event) {
    var rand = Math.floor(Math.random() * 1000);
    $doc.trigger('addItem', rand);
    event.preventDefault();
});