Freigeben über


To observe or not to observe? That is the question…

Lately I’ve been doing a lot of work using KnockoutJS and Durandal. I’ve noticed that many developers fall into a pattern of using observables everywhere in these kinds of applications so I thought it might be good to point out when that is appropriate and when it is not.

There are lots of nifty uses for observables in these types of applications, but one needs to remember that there is a cost to using them. So I am going to make a quick cheat sheet below explaining when to use an observable and when not to.

DO use observables when:

  • you are going to two-way bind the value to the user interface
  • want to watch when the value changes and act based on it
  • need to extend it for validation purposes

DO NOT use observables when:

  • you are only one-time binding the value
  • you do not need to subscribe to changes in the value

I have seen people using observables all the time which slows your pages down and causes more memory consumption. The general rule of thumb is only use observables in the types of scenarios above. Normal variables are fine for other cases.

magnifierAlso, while reviewing lots of others’ code I have noticed a habit of people calling the observable within their KnockoutJS templates. This causes the output to lose its observable nature and effectively converts it to a one-time binding. Like so:

WRONG: <div data-bind=”visible: someVarIsTrue()”>

RIGHT: <div data-bind=”visible: someVarIsTrue”>

WRONG: <div data-bind=”visible: someProperty.subObject()”>

Generally any time you have a set of parenthesis within your binding you are doing it wrong. If you need to do that you should probably look at using computed properties or adding custom bindings for these scenarios.

Hopefully this helps clear up some of the confusion around using observable variables with KnockoutJS and other frameworks. Please feel free to point out anything I missed and I will update the post. Enjoy!

Technorati Tags: KnockoutJS,Knockout,Durandal