我是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":""}
OP想要鏈接一個* Single Viewmodel * –