BetRob
BetRob

Reputation: 251

How to bind multiple Views to a single ViewModel with Knockout.js

I am new to knockout.js and would like to know how to link Multiple Views to a Single ViewModel. I have 3 views in different HTML pages, when I'm in the 3rd page, "onclick" of a button I want to be able to get JSON object of all the 3 Views.

Can anyone please let me know how this can be done using Knockout.js?

Ex: Page 1

 <div data-role="page" id="Page1">
<div data-role="header">
    <h1>Simple counter</h1>
</div>
<div data-role="content">
    <p>You have clicked the button <span data-bind="text: count"></span> times.</p>
    <input data-bind="value: YourName">Your Name: </input>
    <input type="button" value="Convert To JSON" data-bind="click: ConvertToJSON" />

</div>

Page 2

  <div data-role="page" id="Page2">
<div data-role="header">
    <h1>Page2</h1>
</div>
<div data-role="content">
    <p>Hey Hey Hey <span data-bind="text: pagecount2"></span>.</p>  <br />

    This is supposed to be the number from the previous page <span data-bind="text: testspan"></span>
    <input type="button" value="Convert To JSON" data-bind="click: ConvertToJSON2" />
    <script type="text/javascript" >
  var Page2ViewModel = function() { alert("Page2");

     this.pagecount2 = ko.observable(0);
     this.testspan = ko.observable(100);
     this.ConvertToJSON2 = function() {

            var data = ko.toJSON(this); 
            $.ajax({
                type: 'POST',
                url: '/Person/Save',
                data: data,
                dataType: 'json',
                beforeSend: function() {
                    alert(data);
                },
                success: function (data) {
                    alert(data);
                }
            });
        };
    };

    ko.applyBindings(new Page2ViewModel(), document.getElementById("Page2")); 


    </script>     
</div>
<script type="text/javascript">

</script>

when ConvertToJson2 is clicked I want a JSON object with {"count": "", "YourName":"", "pagecount2":"", "testspan":""}

Upvotes: 0

Views: 959

Answers (2)

G&#244;T&#244;
G&#244;T&#244;

Reputation: 8053

You can bind a DOM element and all its children with:

ko.applyBindings(viewModel, domElement);

If you have a common parent (DOM element) with all your views, use it as domElement.

Otherwise you can ko.applyBindings on as many DOM elements as you want with the same viewmodel. Just keep in mind that a DOM element can only be linked to one viewmodel.

Upvotes: 2

Devnegikec
Devnegikec

Reputation: 631

Declare all three viewModel as global objects, without putting var in front of them and they would be available in you code everywhere.

Upvotes: -1

Related Questions