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 ()
against when you would not because at the moment I am just doing trial and error. If the binding throws error or doesn't update values I remove ()
else I put.
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
- jQuery add and remove delay
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 andobject.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:
Knockout's interactive tutorial is also quite nice and well worth going through.
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.
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.
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.Edit
As noted in the comment below, bindings that are expressions, or access properties of observbles, require parens
Note that the last one
person
andisVisisble
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.