C# style getters and setters in KnockoutJS

It's often useful to apply some normalisation/validation to a KnockoutJS observable. The way you do this is pretty obvious if you're at all familiar with Knockout - you use a computed observable so you get some control over what's being set and in that, you reference a private variable. It's very similar to how it works in C# (unsurprising given that Knockout's author is a Microsofty).

Example: Suppose that we want to silently lock a variable between 0 and 1

// private source variable
var _someProperty = ko.observable(0.5);

// exposed variable
this.someProperty = ko.computed({
	read: function() { return _someProperty(); },
	write: function(newVal) {
		newVal = Math.max(0, Math.min(1, newVal));

The gotcha here is that you must use a ko.observable for the private variable. It's not obvious that this should be the case, but it *is* the case, and if you don't use it, various things won't work; the dependency chain breaks and any bindings you've got to someProperty may not update on write. For some reason, the ko.computed type lacks the valueHasMutated() method so it's hard to inform the bindings to re-read the value if the chain doesn't do the work for you.

Talk is cheap

Leave a comment:

HTML is not valid. Use:
[url=http://www.google.com]Google[/url] [b]bold[/b] [i]italics[/i] [u]underline[/u] [code]code[/code]