视图模型有一个可观察的数组simpleSearchResultsArray,它在点击绑定数据 1 按钮时被填充。 我在文件加载时应用绑定。当我单击按钮时,视图模型会更新,但视图不会更新。
这是查看代码:
<table>
<thead id="resultTableHeader">
<tr style="text-align: center" data-bind="foreach: columns">
<th style="text-align: center; height: 23px;" data-bind="visible: checked, text: header">
</th>
</tr>
</thead>
<tbody id="resultTableBody" data-bind="foreach: simpleSearchResultsArray">
<tr>
<td style="text-align: center; vertical-align: middle;">
<span data-bind="text: $index()+1"></span>
</td>
<td style="text-align: center; vertical-align: middle;">
<span data-bind="text: jobName"></span>
</td>
<td style="text-align: center; vertical-align: middle;">
<span data-bind="text:qName"></span>
</td>
</tr>
</tbody>
</table>
<button id="bindData1">bind data 1</button>
<button id="bindData2">bind data 2</button>
视图模型代码:
function SimpleSearchResults() {
var self = this;
self.index = ko.observable();
self.jobName = ko.observable();
self.qName = ko.observable();
};
function QuoteSimpleSearchVM() {
var self = this;
self.simpleSearchResultsArray = ko.observableArray([]);
self.gridOptions = {
columns: [{
header: 'Index',
dataMember: 'index',
checked: ko.observable(true)
}, {
header: 'Job Name',
dataMember: 'jobName',
checked: ko.observable(true)
}, {
header: 'Quote Name',
dataMember: 'qName',
checked: ko.observable(true)
}]
};
self.Search = function (num) {
var temparray = [];
// data1 and data2 to consider as info from service
var data1= [{jobName: 'a', documentName: 'Quote1'},{jobName: 'b', documentName: 'Quote2'}];
for (var k = 0; k < data1.length; k = k + 1) {
var temp = new SimpleSearchResults();
temp.index = k + 1;
temp.jobName = data1[k].jobName;
temp.qName = data1[k].documentName;
temparray.push(temp);
}
self.simpleSearchResultsArray = ko.observableArray([]);
self.simpleSearchResultsArray = ko.observable(temparray);
alert("1");
}
self.UpdateData = function()
{
var temparray=[];
var data2= [{jobName: 'c', documentName: 'Quote2'},{jobName: 'd', documentName: 'Quote4'}];
for (var k = 0; k < data2.length; k = k + 1) {
var temp = new SimpleSearchResults();
temp.index = k + 1;
temp.jobName = data2[k].jobName;
temp.qName = data2[k].documentName;
temparray.push(temp);
}
self.simpleSearchResultsArray = ko.observableArray([]);
self.simpleSearchResultsArray = ko.observable(temparray);
alert(2);
};
};
var QuoteSimpleSearchVMObj;
$(document).ready(function () {
QuoteSimpleSearchVMObj = new QuoteSimpleSearchVM();
ko.applyBindings(QuoteSimpleSearchVMObj.gridOptions, document.getElementById("resultTableHeader"));
ko.applyBindings(QuoteSimpleSearchVMObj, document.getElementById("resultTableBody"));
$("#bindData1").click(function(){
QuoteSimpleSearchVMObj.Search();
});
$("#bindData2").click(function(){
QuoteSimpleSearchVMObj.UpdateData();
});
});
如何在单击绑定数据 1 按钮和绑定数据 2 按钮时更新视图?