observable properties design pattern in javascript
Created
June 16, 2014 22:04
-
-
Save siddharth-pandey/2460ef164fcd2b63a525 to your computer and use it in GitHub Desktop.
A Pen by Sid.
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
<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> |
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
//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