ko.public example

by Andrew Worcester

HTML

<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css">
<script src="https://rawgithub.com/amwmedia/ko.public/master/src/ko.public.js"></script>
<div id="module1">
    <h1 data-bind="text: title"></h1>
    <strong>List Total:</strong> <span data-bind="text: list().length"></span><br />
    <input type="text" data-bind="value: val, valueUpdate:'afterkeydown'" /><br />
    <button data-bind="click: add">add to list</button>
</div>

<hr />
<div id="module2">
    <h1 data-bind="text: title"></h1>
    <input type="text" data-bind="value: val, valueUpdate:'afterkeydown'" /><br />
    <strong>val char count:</strong> <span data-bind="text: val().length"></span><br /><br />
    list values
    <ul  data-bind="foreach: list"><li data-bind="text: $data"></li><ul>
</div>
<a href="https://github.com/amwmedia/ko.public" target="_blank">ko.public on GitHub</a>

JavaScript

function viewModel_1(){
    var vm = this;
    // local observable
    vm.title = ko.observable('This is Module 1');
    
    // public observable (initializing with value)
    // public values can only be initialized once, the
    // first model to give them a value sticks
    vm.val = ko.public('val', 'hello');
    
    // public observable (not yet initialized with a value)
    // but it will be filled in vm2 with an array
    vm.list = ko.public('list');
    
    // allows us to fill our list observable array with
    // new values
    vm.add = function(){
        vm.list.push(vm.val());
        vm.val('');
        console.log(vm.list(), vm.list);
    };
}

function viewModel_2(){
    var vm = this;
    
    // local observable
    vm.title = ko.observable('This is Module 2');
    
    // public observable (value initialized in vm1)
    vm.val = ko.public('val');
    
    // when a public is initialized with an array, the
    // observable is converted to an observable array
    vm.list = ko.public('list', ['hello', 'there']);
}

// because we are initializing the list from vm2, it's
// important that we instatiate our viewmodels prior to 
// applying bindings. otherwise the bindings that are in
// vm1 will be applied against an observable (no array)
// and we'll get errors.
var vm1 = new viewModel_1();
var vm2 = new viewModel_2();

// apply the bindings
ko.applyBindings(vm1, document.getElementById('module1'));
ko.applyBindings(vm2, document.getElementById('module2'));