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']()"></div>
Advertisements

3 thoughts on “Binding to invalid property names with $data in KnockoutJS

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s