JSFiddle - React, Tailwind, and code Playground

by uedatakuya

HTML

<p id="hoge" data-bind="foo">
hogehoge
</p>
<input id="in" type="text"/ data-bind="foo">

JavaScript

// Creating an observable object with property function.
// By using the property function you can set and get a value.
// observable function return the property function
// wihch related with the created observable object.
// The property function can be set callback functions.
// After setting value using the property function, 
// callback funtions will be called.
function observable(init) {
    
    var value = init;
    var callbacks = [];
    var i;

    var property = function(v) {

        // setter
        if (typeof v !== "undefined") {
            value = v;

            // notify to observers
            callbacks.forEach(function(callback){
                if (typeof callback === "function") {
                    callback(this);
                }
            });
        }

        // getter
        return value;
    };

    // add observer
    property.bind = function(callback) {
        callbacks.push(callback);
    };

    // for detection of type
    property.observable = observable;
    return property;
}

var obj1 = {
    foo: observable("foo"),
    bar: observable("bar")
};

function applyOutBinding(node, obj) {
    var key = node.data('bind');
    node.text(obj[key]());
    obj[key].bind(function() {
        node.text(obj[key]());
    });
}

function applyInBinding(node, obj) {
    var key = node.data('bind');
    node.blur(function() {
        obj[key](node.val());
    });
}

applyOutBinding($('#hoge'), obj1);
applyInBinding($('#in'), obj1);