O'Reilly logo

Knockout.js by Jamie Munro

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 7. Enhancing Observables

Extending Observables

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.

Example 7-1. Extending an observable
<!DOCTYPE html>
<html>
<head> 
    <title>Data Binding with KnockoutJS</title>
</head>
<body> 

    <textarea data-bind="textInput: myText"></textarea><br/>
    Characters remaining: <span data-bind="text: charactersRemaining"></span> 

    <script type='text/javascript' src='js/knockout-3.2.0.js'></script> 
    <script type='text/javascript' src='js/maxCharacters.js'></script> 
    <script> 
        function ViewModel() { 
            var self = this; 

            self.maxCharacters = 140; 

            self.myText = ko.observable('')
            .extend({maxCharacters: self.maxCharacters}); 

            self.charactersRemaining = ko.computed(function() { 
                return self.maxCharacters - self.myText().length; 
            }); 
        }; 

        var viewModel = new ViewModel(); 
        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. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required