[英]Updating a knockout observable after an async ajax call using ko.mapping.fromJS
I have a simple use case. 我有一个简单的用例。 I need to call a WS asynchronously and show the returned JSON on the UI.
我需要异步调用WS,并在UI上显示返回的JSON。 The JSON that I get back is an object with multiple properties.
我得到的JSON是具有多个属性的对象。 For simplicity, the code below only has one property.
为简单起见,下面的代码仅具有一个属性。 Since I have multiple properties, I am using ko.mapping.fromJS to map the JSON to the object properties.
由于我具有多个属性,因此我使用ko.mapping.fromJS将JSON映射到对象属性。 It all seems to work, except the fetched data doesn't update on the UI.
似乎一切正常,除了获取的数据不会在UI上更新。 If I manually update the observable, it works.
如果我手动更新可观察对象,则它可以工作。 But not when using ko.mapping.fromJS.
但是在使用ko.mapping.fromJS时不行。
Javascript 使用Javascript
function AppViewModel() {
var self = this;
self.firstName = ko.observable("Bert");
$.ajax({
dataType: 'json',
async: true,
type: 'POST',
url: '/echo/json/',
data: {
json: '{"firstName":"Bob1"}'
}
}).done(function(data) {
console.log(data);
//self.firstName(data.firstName);//This works
self = ko.mapping.fromJS(data); //This doesn't
console.log(self.firstName());
}).fail(function(jqxhr, textStatus, error) {
alert('there was an error');
});
}
// Activates knockout.js
var avm = new AppViewModel();
ko.applyBindings(avm);
HTML HTML
<p>First name: <strong data-bind="text: firstName"></strong></p>
You can run the jsfiddle. 您可以运行jsfiddle。 You will see that this line works
您会看到这行有效
self.firstName(data.firstName);//This works
and this line doesn't work 这行不起作用
self = ko.mapping.fromJS(data); //This doesn't
http://jsfiddle.net/texag93/fakdf5Lw/53/ http://jsfiddle.net/texag93/fakdf5Lw/53/
Two things: 1) You need to create your initial view model with ko.mapping.fromJS
, and 2) you need to pass your existing view model as a second parameter to fromJS
when updating it. 两件事:1)您需要使用
ko.mapping.fromJS
创建初始视图模型,以及2)更新时将现有视图模型作为第二个参数传递给fromJS
。
So something like this instead: 所以像这样:
// Activates knockout.js
var avm = ko.mapping.fromJS({firstName: 'Bert'});
ko.applyBindings(avm);
$.ajax({
dataType: 'json',
async: true,
type: 'POST',
url: '/echo/json/',
data: {
json: '{"firstName":"Bob1"}'
}
}).done(function(data) {
console.log(data);
ko.mapping.fromJS(data, avm);
console.log(avm.firstName());
}).fail(function(jqxhr, textStatus, error) {
alert('there was an error');
});
Updated fiddle: http://jsfiddle.net/fakdf5Lw/56/ 更新的小提琴: http : //jsfiddle.net/fakdf5Lw/56/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.