In our world now a days, no one have time. People want things to happen at this very moment. Waiting is, believe me, is a good old forgotten phenomenon. When it comes to coding, and that too in MVVM pattern where we bind view elements via properties, we too want things to happen instantaneously, we want property to retrieve the value from the view element at the very moment it is inserted.
By default, Knockout JS, do not have the ability to do so. Actually, let’s do an example to see what we are talking about.
Consider the following simplest knockout code, where we have an input box where we type some text, which in turn get displayed in the H1 tag below it.
1: <!DOCTYPE html>
2: <html xmlns="http://www.w3.org/1999/xhtml">
3:
4: <head>
5: <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
6: <title>Untitled Document</title>
7: </head>
8:
9:
10: <body>
11:
12: <input type="text" data-bind="value: textContent"/>
13:
14: <h1 data-bind="text: textContent"></h1>
15:
16: <script src="js/knockout 3.0.0.0.js"></script>
17: <script src="js/ViewModel.js"></script>
18: </body>
19: </html>
Here goes the ViewModel.
1: var ViewModel = function(){
2: this.textContent = ko.observable();
3: }
4:
5: ko.applyBindings(new ViewModel());
Now when you run the code, you would see that nothing would displayed in H1 tag unless you tab out from the input box.
So! Well, lets add one more property where we did binding of “textcontent” observable in our view. So our code would be like.
1: <input type="text" data-bind="value: textContent, valueUpdate:'afterkeydown'"/>
If you see closely, the property valueUpdate: ‘afterkeydown’ tells knockout that this property should update as soon as a key is pressed. (You could also choose ‘aftermouseover’, ‘afterblur’ etc events for updating the property.) Save the code and run it in browser again and here’s how the result would be like.
You could see that the text started updating in H1 as soon as I type it in the text box.
Hope you’ve enjoyed this quick post.
Happy reading!!!
Cool
ReplyDelete