Last active
September 20, 2016 15:50
-
-
Save calvimor/3585b33f56a002d51274fbd584835b38 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var Book = function (name, price) { | |
var priceChanging = [], | |
priceChanged = []; | |
this.name = function (val) { | |
return name; | |
}; | |
this.price = function (val) { | |
if(val !== undefined && val !== price) { | |
for (var i = 0; i < priceChanging.length; i++) { | |
if(!priceChanging[i](this, val)) { | |
return price; | |
} | |
} | |
price = val; | |
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('JavaScript: The Good Parts', 23.99); | |
console.log('The name is: '+ book.name()); | |
console.log('The price is: $' + book.price()); | |
book.onPriceChanging(function (b, price) { | |
if (price > 100) { | |
console.log('System error, price has gone unexpectedly high'); | |
return false; | |
} | |
return true; | |
}); | |
book.onPriceChanged(function (b) { | |
console.log('The book price has changed to: $' + b.price()); | |
}); | |
book.price(19.99); | |
book.price(20); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Added return values for name and price properties methods