Skip to content

Instantly share code, notes, and snippets.

@syaifulsz
Last active January 21, 2020 07:14
Show Gist options
  • Save syaifulsz/8d53b3fa9c1dc5f9e35cc7164e20733e to your computer and use it in GitHub Desktop.
Save syaifulsz/8d53b3fa9c1dc5f9e35cc7164e20733e to your computer and use it in GitHub Desktop.
Simple ES Javascript Plugin for Data Manager & Observer (Single state of truth)
window.DataManager = {
setData: function ( data ) {
if ( typeof data !== 'object' ) {
throw new Error( 'Only accept object!' );
}
var hashPrevData = JSON.stringify( DataManager.data );
var hashData = JSON.stringify( data );
if ( hashPrevData !== hashData ) {
DataManager._prevData = _.cloneDeep( DataManager._data );
DataManager._data = _.merge( DataManager.data, data );
for ( var i in DataManager.observer ) {
var observeCallback = DataManager.observer[ i ];
observeCallback( DataManager.data, DataManager.prevData );
}
}
},
get data() {
return DataManager._data;
},
get prevData() {
return DataManager._prevData;
},
set observer( callback ) {
if ( typeof callback !== 'function' ) {
throw new Error( 'Only accept function!' );
}
DataManager._observers.push( callback );
},
get observer() {
return DataManager._observers;
},
_observers: [],
_data: {},
_prevData: {}
};
// Example register `observer` callback
DataManager.observer = function( data, prev ) {
// example usage with previous data
if ( prev.name ) {
console.log( 'Bye ' + prev.name + '!' );
}
console.log( 'Hello ' + data.name + '!' );
};
// Example set data
DataManager.setData( { name: 'Syaiful' } );
// Hello Syaiful!
// Example set data and use previous data
DataManager.setData( { name: 'Arifah' } );
// Bye Syaiful!
// Hello Arifah!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment