Skip to content

Instantly share code, notes, and snippets.

@siddharth-pandey
Created June 16, 2014 22:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save siddharth-pandey/17ae0c4731e97c9d3e94 to your computer and use it in GitHub Desktop.
Save siddharth-pandey/17ae0c4731e97c9d3e94 to your computer and use it in GitHub Desktop.
A Pen by Sid.
<h1>observable properties design pattern in javascript</h1>
<h2>points to know</h2>
<ul>
<li>in .net we normally use inotifypropertychanged interface to notify if something was changed. in .net we can have properties with method bodies.</li>
<li>in js, properties are really just public fields in .net i.e. with the lack of method body.</li>
<li>so, in js, we can use methods-as-properties pattern like a c# get; set; feature. eg. knockout library uses this pattern. </li>
</ul>
//observable properties design pattern in javascript
var Book = function (name, price){
//crate to arrays to store the price to compare the new prices.
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('JS book',20.98);
console.log('the name is ' + book.name());
console.log('the price is $' + book.price());
book.onPriceChanging(function(b, price){
if(price > 100){
console.log('price is to 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(219.99);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment