December 2014
Intermediate to advanced
102 pages
1h 45m
English
Observables by themselves can accomplish quite a bit. Of course, there are times with every framework that it simply cannot do everything you want. Knockout provides the ability to write custom functions to extend any observable.
Example 7-1 will extend (pun intended) the previous example that counted characters to prevent the text input from entering more than the allotted amount.
<!DOCTYPE html><html><head><title>Data Binding with KnockoutJS</title></head><body><textareadata-bind="textInput: myText"></textarea><br/>Characters remaining:<spandata-bind="text: charactersRemaining"></span><scripttype='text/javascript'src='js/knockout-3.2.0.js'></script><scripttype='text/javascript'src='js/maxCharacters.js'></script><script>functionViewModel(){varself=this;self.maxCharacters=140;self.myText=ko.observable('').extend({maxCharacters:self.maxCharacters});self.charactersRemaining=ko.computed(function(){returnself.maxCharacters-self.myText().length;});};varviewModel=newViewModel();ko.applyBindings(viewModel);</script></body></html>
In the previous example, the myText observable has been extended to call the maxCharacters function, passing in a variable that contains the max characters to allow (see Example 7-2).
The maxCharacters function has been placed inside a file called maxCharacters.js and placed within the previously created js folder. ...
Read now
Unlock full access