KnockoutJS bindings

by ospatil

HTML

<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="http://github.com/downloads/SteveSanderson/knockout/knockout-2.1.0.js"></script>
<h3>Binding and computed properties</h3>
<div>
    <label for="firstName">First Name:</label>
    <input name="firstName" 
            type="text" 
            data-bind="value: firstName" 
            placeholder="Enter first name"/>
    <label for="lastName">Last Name:</label>
    <input name="lastName"
            type="text"
            data-bind="value: lastName"
            placeholder="Enter last name"/>
    <label>Full Name:</label>
    <span class="input uneditable-input" data-bind="text: fullName"></span>
    <h3>Binding Arrays</h3>
    <div>
        <button class="btn btn-mini" type="submit" data-bind="click: addItem">Add item</button>    
        <ul data-bind="foreach: items">
            <li data-bind="text: $data"></li>
        </ul>
        <div>Since there is no scoping and multiple ViewModels is not the standard practice and though you can have them, you can't nest them. <a href="https://groups.google.com/d/msg/knockoutjs/y0abZNFtOxU/nonvhwQq3q0J">Check this out.</a></div>
        <div>Full Name: <span class="label label-important">Not Applicable</span></div>
    </div>
</div>

JavaScript

function AppViewModel() {
    self = this;
    self.firstName = ko.observable('');
    self.lastName = ko.observable('');
    self.items = ko.observableArray([1, 2, 3]);
    self.counter = 3;
    
    self.fullName = ko.computed(function() {
        return self.firstName() + ' ' + self.lastName();                
    }, this);

    self.addItem = function() {
        self.items.push(++self.counter);            
    }
}

ko.applyBindings(new AppViewModel());