Binding to invalid property names with $data in KnockoutJS

A quick tip when working with KnockoutJS: if you are binding a value to a property with a valid name then it is very simple to get at the value in your HTML…

ViewModel = function() {
	this.value = ko.observable("Hello World");
};

ko.applyBindings(new ViewModel());
...

<div data-bind="text: value"></div>

But things are not quite as simple when you have a property value that has a space (or other invalid character) in the name:

ViewModel = function() {
  this['value with space'] = ko.observable('Hello World');
};

To bind to this value, we need to use the $data variable that for some reason is not really covered in the Knockout documentation (though it is mentioned here).

The $data variable will always return the object that is currently being bound (think DataContext for any WPF developers), and we can use it to access the value of our property through the indexer as we would in vanilla JS:

<div data-bind="text: $data['value with space']()" />