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 ()
I feel like the existing answers skip over a very important point of confusion: data-bind
attributes.
It is true that you use the parens when you are in Javascript, and getting or setting observables. But when you are writing data-bind="text: property"
, you leave out the parens even when working with observables.
As noted in the comment below, bindings that are expressions, or access properties of observbles, require parens
visible: personName().length > 0
visible: person().Name().length > 0
visible: person().isVisible
Note that the last one person
and isVisisble
are both observables, but the last property doesn't use parens! The reason for this is that we would be passing a value to the binding instead of an observable, and it wouldn't update.
Basically whenever you're working with an observable value (array or otherwise) you should use the parentheses to get the value and set the value.
var something = ko.obserbable();
something(5); //set value
console.log(something()); //get value: 5
The reason being that most JS implementations do not support getters and setters for properties yet, so observables were implemented like this to get around this limitation.
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.