JSFiddle - React, Tailwind, and code Playground

by TrueBlueAussie

HTML

<div id="test">10</div>
<input id="button2" type="button" value="Add 2" />
<input id="button10" type="button" value="Add 10" />

JavaScript

var Foo = (function () {
    "use strict";
    
    // Constructor
    function Foo($element, options){
        this.$element = $element;
        this.options = options
        this.fooVal = 0;
    }
    
    // Create method (called from bridge)
    Foo.prototype.onCreate = function(){
        this.fooVal = ~~this.$element.text()
    };

    // Add the specified val to the elements current value    
    Foo.prototype.add = function (val) {
        this.fooVal += val;
        // Update the element text with the new value
        this.$element.text(this.fooVal);
    };
    return Foo;
})();

// Create a bridge to each element that needs a Foo
$.fn.foo = function (options, args) {
    this.each(function () {
        var $element = $(this);
        // Try to get existing foo instance
        var foo = $element.data("Foo");
        // If the argument is a string, assume we call that function by name
        if (typeof options == "string") {
            foo[options](args);
        }
        else if (!foo) {
            // No instance. Create a new Foo and store the instance on the element
            foo = new Foo($element, options);
            $element.data("Foo", foo);
            // Record the connected element on the Foo instance
            foo.$element = $element;
            // Call the initial create method
            foo.onCreate();
        }
    });
}

// testing
console.clear();
$('#test').foo();
$('#button2').click(function () {
    $('#test').foo("add", 2);
});

$('#button10').click(function () {
    $('#test').foo("add", 10);
});