JSFiddle - React, Tailwind, and code Playground

by houssamk

HTML

<input type="text" id="myInput" value="">

JavaScript

var MySingleton = (function () {

    // PRIVATE properties
    var inputTxt = '#myInput' // css selector
    var instance;
    var dataModel;
    
    

    // singleton pattern //
    function MySingleton() {
        // instance exists return it
        if (instance) {
            return instance;
        }
        
        // create new instance
        instance = this;        
        // PUBLIC
        this.DataModel = function () {
            return dataModel || (dataModel = initDataModel());
        };        
        // PRIVATE
        bindEventHandlers();
        return instance;
    }
    // //
    
    
    // PRIVATE METHODS
    var initDataModel = function () {
        return {
            id: '',
            name: '',
            age: ''
        };
    };
    
    var bindEventHandlers = function () {
        $(inputTxt).change(eventHandler);
    };
    
    var eventHandler = function(){
        alert('new value:' + $(inputTxt).val());
    };

    // PUBLIC
    return {
        getInstance: function () {
            return instance || new MySingleton();
        }
    };
})();

var myInstance = MySingleton.getInstance();
$('#myInput').val('abc').change();
myInstance = MySingleton.getInstance();
$('#myInput').val('def').change();