2014-06-10 64 views
0

我是knockout.js的新手,並想知道如何將多個視圖鏈接到單個ViewModel。我在不同的HTML頁面中有3個視圖,當我在第3頁時,我想要能夠獲得所有3個視圖的JSON對象的按鈕「onclick」。如何使用Knockout.js將多個視圖綁定到單個ViewModel

任何人都可以讓我知道如何使用Knockout.js完成這項工作嗎?

例如: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> 

第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> 

ConvertToJson2點擊我想{"count": "", "YourName":"", "pagecount2":"", "testspan":""}

回答

-1

申報JSON對象全部三個視圖模型作爲全局對象,而不把var放在他們面前,他們將在你處處可用。

+0

OP想要鏈接一個* Single Viewmodel * –

2

可以綁定一個DOM元素及其所有孩子:

ko.applyBindings(viewModel, domElement); 

如果你有一個共同的父(DOM元素)與所有的美景,用它作爲domElement

否則,您可以使用相同的視圖模型在任意多的DOM元素上使用ko.applyBindings。請記住,DOM元素只能鏈接到一個視圖模型。

相關問題