Remember the Parentheses on Your Knockout Observables

When you use KnockoutJS for data binding, you'll generally want to be binding to observable properties exposed from your ViewModel objects. An observable is an object declared with knockout:

{ customerName = ko.observable("");}

When you go to set that property, remember to call it as a function object with a call like:

customerName("Homer"), as opposed to customerName = "Homer"

When you get the value, you likewise call it as a function:

var name = customerName() 

This trips up even the most experienced Knockout programmers. As a result, you might want to check out either this post on Steven Sanderson's blog or this Durandal documentation page for ways to leave off the parentheses when working with observables.

Brian Noyes is the CTO of Solliance Inc. (solliance.net), a Microsoft regional director and MVP, and Pluralsight author.

Posted by Brian Noyes on 04/16/2015


Keep Up-to-Date with Visual Studio Live!

Email address*Country*