JSFiddle - React, Tailwind, and code Playground

by gschutz

JavaScript

var data = [
	{name: 'Barney', foo: 'bar'},
	{name: 'Joe', foo: 'giz'},
	{name: 'Marry', foo: 'moo'},
];


var Binding = function(data) {

	var dispatch = {};

	this.on = function(fnName, callback) {
		if (_.isString(fnName)) {
			dispatch[fnName] = callback;
		}
		return this;
	}

	Object.observe(data || this, function(changes){

	    var add = _.select(changes, {type: 'add'})[0];

	    var remove = _.select(changes, {type: 'delete'})[0];

	    var update = _.select(changes, {type: 'update'})[0];

	    if (add && dispatch.add && _.isFunction(dispatch.add)) {
        	dispatch.add({
        		key: add.name,
        		value: add.object[add.name]
        	}, add);
	    } else if (remove && dispatch.remove && _.isFunction(dispatch.remove)) {
        	dispatch.remove({
        		key: remove.name,
        		value: remove.oldValue
        	}, remove);
	    } else if (update && dispatch.update && _.isFunction(dispatch.update)) {
        	dispatch.update({
        		key: update.name,
        		value: update.object[update.name]
        	}, update);
	    }
	});

	return this;
}

Array.prototype.binding = Binding;
Object.prototype.binding = Binding;


data.binding()
	.on('add', function(newValue, changes) {
		console.log(newValue, changes);
	});


var godzi = {
	foo: 'foo',
	bar: 'bar'
};

godzi.binding()
	.on('add', function(newValue, changes) {
		console.log(newValue, changes);
	})
	.on('remove', function(newValue, changes) {
		console.log(newValue, changes);
	})
	.on('update', function(newValue, changes) {
		console.log(newValue, changes);
	})

// tests

// add
setTimeout(function() {
    godzi.giz = "gizmo";
}, 1000);

// remove
setTimeout(function() {
    delete godzi.foo;
}, 2000);

// update
setTimeout(function() {
    godzi.bar = "new bar";
}, 3000);