我是Knockout Js的新手,我正在使用Knockout Mapping Plugin将我从服务器收到的JSON数据转换为UI Elements。我能够第一次正确加载内容,但是对数据的后续更改根本不会更新UI。
我的html文件有这个(我可以在脚本中控制其可见性)
<div id="Results" style="font-family: Tahoma,Verdana,sans-serif;font-size: 10pt; visibility: hidden" >
<form>
<h4>List of all Arguments</h4>
<ul data-bind="foreach: arguments">
<li> Argument: <span data-bind="text: argumentName"> </span>: <input data-bind="value: defValue"/> </li> </ul>
</form>
</div>
javascript函数有这段代码,
function displayArguments(data){
var page=document.getElementById('Results');
page.style.visibility='visible';
var viewModel = ko.mapping.fromJS(data);
ko.mapping.fromJS(data, viewModel);
if(applyBindingsInvokedAlready == 0){
// applyBindingsInvokedAlready is global default to 0
ko.applyBindings(viewModel);
applyBindingsInvokedAlready =1;
}
}
我想提一下,在发布此问题之前,我已尝试过以下步骤
我迷路了! :(
请帮我弄清楚我在这里犯的错误。 在此先感谢!
答案 0 :(得分:0)
问题是你在写你现有的vm时 您应该检查vm是否已定义,如果是,则执行此类操作
KnockoutJS and binding a single object to a viewmodel
var viewModel;
function displayArguments(data){
var page=document.getElementById('Results');
page.style.visibility='visible';
if(!!viewModel){
viewModel.prop1(data.prop1); // obviously prop1 is not what you use, I just dont
know whats in your model
viewModel.someObservableArray(data.someObservableArray);
}else
{
viewModel = ko.mapping.fromJS(data);
ko.mapping.fromJS(data, viewModel);
if(applyBindingsInvokedAlready == 0){
// applyBindingsInvokedAlready is global default to 0
ko.applyBindings(viewModel);
applyBindingsInvokedAlready =1;
}
}