Skip to content

Instantly share code, notes, and snippets.

@rnaffer
Last active October 27, 2015 03:33
Show Gist options
  • Save rnaffer/7dd1e511e6ccd4bcf54e to your computer and use it in GitHub Desktop.
Save rnaffer/7dd1e511e6ccd4bcf54e to your computer and use it in GitHub Desktop.
Ejemplo del patrón de diseño "Observable Properties" con explicación.
// Permite reaccionar a valores que están cambiando dentro del objeto.
// Asemeja al data binding (iNotifyPropertyChanged) en c#.
// Utiliza los métodos como propiedades en ves de campos publicos. Como hace el framework Knockout.js
// prieceChanging y prieceChanged son arreglos que almacenarán los métodos que se ejecutarán en esos casos.
var Book = function( name, price ) {
var priceChanging = [],
priceChanged = [];
this.name = function( value ) {
return name;
};
this.price = function( value ) {
var i = 0,
length = priceChanging.length;
if ( value !== undefined && value !== price ) {
for ( ; i < length; i++ ) {
if ( !priceChanging[i](this, value) ) {
return price;
}
}
price = value;
i = 0;
length = priceChanged.length;
for ( ; i < length; i++ ) {
priceChanged[i]( this );
}
}
return price;
}
this.onPriceChanging = function( callback ) {
priceChanging.push( callback );
};
this.onPriceChanged = function( callback ) {
priceChanged.push( callback );
};
};
// Caso práctico
var book = new Book( "Javascript: The Good Parts", 23.99 );
console.log( "The name is: " + book.name() );
console.log( "The price is: $" + book.price() );
// Función que será empleada cuando la propiedad esté cambiando
book.onPriceChanging(function( b, price ) {
if ( price > 100 ) {
console.log("System error, price has gone unexpectedly high");
return false;
}
return true;
});
// Función que será empleada cuando la propiedad cambie
book.onPriceChanged(function( b ) {
console.log( "Price has been changed to " + b.price() );
});
book.price( 25.99 );
book.price( 103.99 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment