Monday, October 29, 2012

KnockoutJS tip : when to use brackets?

I simply love the knockout.JS framework. It makes the migration from silverlight to javascript / html so much more comfortable.

One point of confusion in knockout JS you might feel is when do you have to use brackets in front of observable and when can you ignore them? 

e.g. in the knockout intro tutorial : http://learn.knockoutjs.com/#/?tutorial=intro 

This: 

will work just as well as: 


Then whats the difference?  is actually a function since ko.observable returns a function : 



My solution:
In code ALWAYS use ().You have to, otherwise you will remove the ko.observable function on assignment which is bad. And on reading you would get the function not the value you wanted. 

In simple data-bind attributes NEVER use (). Because it will not work to two way data binding, i.e If I had bound value: firstName() to the input it would not have worked.  

In calculated data-bind attributes e.g. value: firstName() + lastName() , use brackets since you want one way binding and basically running arbitrary javascript :) 

Enjoy! 

1 comment: