I am a beginner in Knockout and I must say I often get confused regarding when to use ()
. Is there any general tip/trick regarding when would you use ()>
You use ()
in knockout when using observables or when executing any other method.
Knockout observables are functions, invoked to return you what you looking for or allow you to assign new values.
In knockout you use object.property()
to retrieve a value and object.property(newValue)
to assign a value to that property.
On the knockout website checkout the documentation, specifically the section on observables, which shows you the use of the ()
when querying and writing observables.
To quote:
var myViewModel = {
personName: ko.observable('Bob'),
personAge: ko.observable(123)
};
To read the observable’s current value, just call the observable with no parameters. In this example, myViewModel.personName() will return 'Bob', and myViewModel.personAge() will return 123.
To write a new value to the observable, call the observable and pass the new value as a parameter. For example, calling myViewModel.personName('Mary') will change the name value to 'Mary'.
To write values to multiple observable properties on a model object, you can use chaining syntax. For example, myViewModel.personName('Mary').personAge(50) will change the name value to 'Mary' and the age value to 50.
Knockout's interactive tutorial is also quite nice and well worth going through.