<script type="text/html" id="person-template">
<tr><td>
<p>Book Title: <h3 data-bind="text: Title"></h3>
<p>Available City: <span data-bind="text: CityName"></span></p>
</td></tr>
</script>
jQuery(document).ready(function () {
var loData = AjaxCall('default.aspx', 'GetBookData', '10');
var Data = JSON.parse(loData.Data);
function MyViewModel() {
this.people = Data.Table
}
ko.applyBindings(new MyViewModel());
});
$("#btnChangData").click(
var loData = AjaxCall('default.aspx', 'GetBookData', '20');
var Data = JSON.parse(loData.Data);
ko.cleanNode($("#list")[0]);
$('#sample').empty();
$('#sample').html('<tbody id="list" data-bind="template: { name: "person-template", foreach: people }" ></tbody>');
function MyViewModel() {
this.people = Data.Table
}
ko.applyBindings(new MyViewModel());
);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<table id="sample">
<tbody id="list" data-bind="template: { name: 'person-template', foreach: people }" >
</tbody>
</table>
&#13;
我已将文档就绪函数的数据加载到表中。但是在按钮单击事件中我需要将新的数据源加载到表中,如何将数据源重新绑定到敲除模板..在上面的代码抛出的单击事件中 隐藏复制代码 您不能多次将绑定应用于同一元素 控制台错误..
答案 0 :(得分:2)
欢迎来到Knockout。现在请停止编写jQuery。
每次数据更改时,您都不需要创建新的视图模型。您的viewmodel旨在为整个应用程序建模。您创建并绑定它一次。
你的表应该是一个可观察的,这是一个setter-getter函数,它是Knockout的基础。要为其分配新数据,请将新数据传递给它:
viewmodel.people(Data.table)
如果你没有通过Knockout tutorial,你应该这样做。淘汰比你做的更容易。
更新:您的JavaScript应如下所示:
jQuery(document).ready(function() {
var loData = AjaxCall('default.aspx', 'GetBookData', '10');
var Data = JSON.parse(loData.Data);
function MyViewModel() {
var self = this;
this.people = Data.Table;
this.changeData = function() {
var loData = AjaxCall('default.aspx', 'GetBookData', '20');
var Data = JSON.parse(loData.Data);
self.people(Data.Table);
};
}
ko.applyBindings(new MyViewModel());
});
答案 1 :(得分:0)
i have tried below code and its worked for me, i have declare viewmodel globally
var vm;
var viewModel = function () {
var self = this;
this.people = ko.observableArray([]);
this.updatedata = function (data) { ko.mapping.fromJS(data, {}, self.people); } };
and on page load
vm = new viewModel(); vm.updatedata(Data.Table); ko.applyBindings(vm);
and for data update vm.updatedata(Data)