Skip to content

Instantly share code, notes, and snippets.

@drzippie
Created July 1, 2017 18:13
Show Gist options
  • Select an option

  • Save drzippie/353ac51edae2988190e224e3e82438f9 to your computer and use it in GitHub Desktop.

Select an option

Save drzippie/353ac51edae2988190e224e3e82438f9 to your computer and use it in GitHub Desktop.
systemManager.classes.SystemValue = function( code , callback ) {
var currentValue = null ;
var callbacks = [] ;
var id = code ;
// El objeto tiene una propiedad code y solo lectura con un valor en el constructor
Object.defineProperty( this , 'code', {
value: code,
writable: false
});
// value, que antes de un cambio puede ejecutar 1 o varias funciones, si una
// devuelve false, no se ejecutan el resto y no se cambia el valor
Object.defineProperty(this, 'value', {
get: function() {
return currentValue ;
},
set: function(newValue) {
if ( newValue === currentValue ) {
return ;
}
var isOk = { 'value' : true } ;
// hack: en el loop this = isOk
// simple -> si uno de los callbacks devuelve false
// no se ejecutan el resto
callbacks.forEach( function( event ) {
// this == isOk !!!
if ( this.value === false ) {
return ;
}
var result = event( id , newValue, currentValue );
if ( result === false ) {
this.value = false ;
}
} , isOk ); // el segundo parametro, será this dentro de la función
if ( isOk.value ) {
currentValue = newValue;
}
}
});
this.addCallback = function( callback , isFirst ) {
isFirst = isFirst || false
if ( typeof callback !== 'function') {
return ;
}
if ( isFirst ) {
callbacks.unshift( callback);
return ;
}
callbacks.push( callback);
}
this.addCallback( callback ) ;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment