When to Not Use Observable in KnockoutJS


javascriptI've been really busy lately and my list of things to blog on has been getting backed up. One thing that occurred to me while building my new JavaScript course was about how KnockoutJS and Observables actually work. Here's the deal.

KnockoutJS supports the idea of an observable object. This is similar to WPF/XAML concept of INotifyPropertyChanged interface. Most KnockoutJS dev's I've talked with use KnockoutJS's observable everywhere. But there are cases when you don't need it.

The biggest problem I see is that some people think that to get two-way binding you need observable.  For example, here is a JSFiddle with a typical (but simple) KnockoutJS example:

Here you see that the view model (e.g. src) is using an observable to create the properties. In the HTML, we have the name field bound twice...to the input box and to a div. This means than when we change the text in the first input box and that box loses focus, then the div changes as well. This is at the heart of what KnockoutJS's observable does. But in some cases, if you don't need the notification part of the functionality, a simple property is more efficient:

In this case, the code is identical but the viewmodel (e.g. src) is just using plain old JS members. While changing the text in the name input field doesn't make the div change (because the notification is missing), it does in fact handle two way binding. You can see this if you click the button (which pops up an alert showing the name in the view model.

For large apps that have a lot of bindings, this efficiency is helpful. Knowing when you can avoid using observable can help improve overall KnockoutJS performance.

What do you think?


Bootstrap 4 is Here!

After a long development cycle, Bootstrap has been completely re-written to improve performance and be more consistent. Learn Bootstrap 4 now with my Wilder Minds course:

Enroll Today


Shawn
Shawn Wildermuth
Author, Teacher, and Coach




My Courses

Wilder Minds Training
Vue.js by Example (Now Available)
Bootstrap 4 by Example
Intro to Font Awesome 5 (Free Course)
Pluralsight
Less: Getting Started (Coupon Available)
Building a Web App with ASP.NET Core, MVC6, EF Core, Bootstrap and Angular (updated for 2.1)
Using Visual Studio Code for ASP.NET Core Projects
Implementing ASP.NET Web API
Web API Design

Application Name WilderBlog Environment Name Production
Application Ver v4.0.30319 Runtime Framework x86
App Path D:\home\site\wwwroot\ Runtime Version .NET Core 4.6.27019.06
Operating System Microsoft Windows 10.0.14393 Runtime Arch X86