I can easily understand how it works in C#, but in Javascript I'm a little bit confused. Here is a little test code I wrote:
function Lunch(name,price)
{
var priceChanging = [], priceChanged = [];
this.name = function(val)
{
return name;
}
this.price = function(val)
{
if(val !== price && val !== undefined )
{
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(val)
{
priceChanging.push(val);
}
this.OnPriceChanged = function(val)
{
priceChanged.push(val);
}
}
var order = new Lunch("Fish and Chips",20);
console.log(order.name());
console.log(order.price());
order.OnPriceChanging(function(name,price)
{
if(price > 30)
{
console.log("Price too high");
return false;
}
return true;
});
order.OnPriceChanged(function(name)
{
console.log("Price changed to: $" + name.price());
});
It runs fine, the thing is I want to be able to explain it to myself. I'm not in front of a debugger and just used Notepad at the moment. I just thought of it like .NET where subscribers are put in a container, I'm just curious how it works in Javascript.
Does the OnPriceChanging and OnPriceChanged function call themselves automatically anytime you add/change the price? I guess I'm just uncomfortable with how Javascript is loosely typed and all.
As always, I'm very thankful for all the imparted knowledge.