Saturday, 24 November 2012

Caution: extending Knockout's default bindings

So I'm working on a feature that requires that every input be sent to the server after a user types in the data. What a better way than to decorate the default "value" binding. My initial binding looks like this:
                     ko.bindingHandlers.trackedInput = {  
                          init : function(element, valueAccessor, allBindingsAccessor) {  
                               ko.bindingHandlers.value.init(element, valueAccessor, allBindingsAccessor);  
                          },  
                          update : function(element, valueAccessor) {  
                               track($(element));  
                               ko.bindingHandlers.value.update(element, valueAccessor);  
                          }  
                     }  
However, when I ran this, I got this error:
Uncaught TypeError: undefined is not a function
Upon digging into the source code, I found that the default 'value' binding actually requires a 3rd param that needs to passed in. So the correct way is this:
 ko.bindingHandlers.trackedInput = {  
                          init : function(element, valueAccessor, allBindingsAccessor) {  
                               ko.bindingHandlers.value.init(element, valueAccessor, allBindingsAccessor);  
                          },  
                          update : function(element, valueAccessor) {  
                               track($(element));  
                               ko.bindingHandlers.value.update(element, valueAccessor);  
                          }  
                     }  
                     vm = {choice : ko.observable()};  
                     ko.applyBindings(vm);  
                });  

No comments:

Post a Comment