Observables sample

by lazyberezovsky

JavaScript

var Book = function(title, price) {
    var priceChanging = [],
        priceChanged = [];
    
    this.title = function(value) {
        return title;
    };
    
    this.price = function(value) {
        if (value !== undefined && value !== price) {            
            for(var i = 0; i < priceChanging.length; i++) {
                 if (!priceChanging[i](this, value))
                     return price;
            }
            
            price = value;
            for(var i = 0; i < priceChanged.length; i++) {
                priceChanged[i](this);
            }
        }
        
        return price;
    };
    
    this.onPriceChanging = function(callback) {
        priceChanging.push(callback);
    };
    
    this.onPriceChanged = function(callback) {
        priceChanged.push(callback);
    };
};

var book = new Book("Patterns", 39.99);
console.log('Title:' + book.title());
console.log('Price:' + book.price());

book.onPriceChanging(function(b, price) {
    if (price > 50) {
        console.log('Price ' + price + ' is too high');
        return false;
    }    
    return true;
});

book.onPriceChanged(function(b) {
    console.log('Price: ' + b.price());
});

book.price(20);
book.price(70);
console.log('Price:' + book.price());