For one of my pet project, I got into a situation where I needed to get the values of a form somehow, and use it to create and save a new entity on the server without leaving the current page, and also update the list of displayed elements on the page.
I though of using JQuery’s ability to get div elements and their text…but it just didn’t feel right. I needed something more than that to help resolve this situation…something to Knock this problem out. The solution: KnockoutJs.
What is KnockoutJs?
KnockoutJs is a library meant for the creation of dynamic UIs the ***right way***. It comes with one very interesting feature: model binding, which it provides using a MVVM architecture. For .Net developers like me, think of it as using Silverlight or WPF with their binding features but on web elements.
This short description does not do it justice. For more information, please ch[eck it out here.
Because my particular form needed a drop down with the values of some of my enums, I wrote this helper class
Here’s the result:
Word of warning: you should always put your script tag at the end of the page or after defining the div element you are going to bind the view model to. For whichever reason, whenever I placed it somewhere else, it didn’t work.
You might have noticed that I am calling my observable properties as if they were methods. This the way they need be called to return the data the observables contain. On the view itself, I use the data-bind attribute. This is how I specify the binding back to the model. There are various binding options, such as value binding, text binding, option binding and click binding.
Using KnockoutJs was clean and simple…so clean that inspired these lyrics based on LL Cool J’s “Mama said knock you out” song:
Rocking its peers, and putting beginners to tears.
KnockoutJs is gonna take this itty bitty Developer World by storm,
And you’ve just been warned.