Writing Better Javascript With KnockoutJS

Programming to the DOM is significantly different then server-side programming.  In the past, I’d basically use raw javascript and jquery to get the job done.  However, I’d often run into the problem of my code getting so unmanageable I’d lose some of my hair ( as you can see from my picture) .  I knew that there had to be a better way.  There are a growing number of front-end frameworks out there.  I have dabbled with both Backbonejs and Angularjs in the past and I thought they were both pretty good.  However, I never gained serious proficiency.  I was recently building out an E-Learning site and I really wanted to to try out some new things.  First of all I wanted to use the new WordPress REST API.  I knew that if I was going to build the site this way, I would also need to write out a lot of javascript since there would be a good amount of api calls.  I also knew that I could not afford to deal with spaghetti javascript.

Introducing KnockoutJS

I decided to go with KnockoutJS primarily because it is lighter weight than any of the other libraries that I saw out there.  Knockout is not a full MVC framework like Angular or Backbone.  It is a “Model-View-ViewModel” framework (MVVM for short).   For those of us that are used to MVC, there is no controller that binds models to the view, but rather a viewmodel is used for this.  My understanding of this is that we would basically create all the parts of the view in the view model.  The view model is a data representation of the entire page that is being loaded.  The models are basically data representations of the individual parts.  The ViewModel consists of each of the different models.  Finally the view is basically the markup that is rendered through you ViewModel and Models.

Programming javascript in this way took some time to get used to.  I was so used to writing javascript in a more linear way.  With this new methodology, I need to think of all the elements of the DOM as small pieces of data.  If I needed to write an AJAX call, I’d write one one the fly.  If I needed a click handler, I’d do the same thing.  Now I basically need to look at the entire DOM and plan things out.  This does make things a little bit more complicated initially and there is a real learning curve.  However, I have found my code to be much easier to maintain.