Wednesday, August 08, 2012

Useful code snippets for knockoutjs - Part 1

1. Function 'deferComputed' to create a computed observable with deferred evaluation.

Many times we want to create  'computed' observable with deferred evaluation. The syntax to create it is somewhat complex. So this is just a convenience function.

 deferedComputed = function(readfunc){  
   return ko.computed({read:readfunc, deferEvaluation:true});  

Now to create deferred computed observable, you can use var
 deferedObs = deferedComputed(function() { /* code to compute the observables value */ });  

2. yes/no binding:

Suppose you have observable that contains a Boolean value (true/false), many times it is not appropriate to display this value as 'true/false'. It is better to display this value as 'yes or no'.  'YesNo' binding converts a boolean variable into 'yes' or 'no' text.

 ko.bindingHandlers.yesno = {  
   update: function(element,valueAccessor){  
     var text = 'no';  
     var value = ko.utils.unwrapObservable(valueAccessor());  
     if(value) { text = 'yes'; }