我似乎无法弄清楚如何将多个源与knockoutjs的映射插件合并在一起。在下面的代码中,我尝试将不同的请求映射到相同的可观察集合中,但只添加了最后一个请求。
this.dataSets = mapper.fromJS([], {
key: (data) => data.dataSetKey,
create: (options) => {
console.log(options.data);
var item = new FxsPortal.FxsSelectable<AscendDataSet>(
mapper.fromJS(options.data, {
'copy': ["cameraInfo"]
}));
return item;
}
});
userStore.get().subscriptions.forEach(subscription => {
this.logger.logInformation("Iterating Subscription", subscription);
(xhr = $.ajax({
beforeSend: (xhr) => xhr.setRequestHeader('Authorization', "Bearer " + OAuthModule.getStoredTokens().access_token),
type: 'GET', url: AppOptions.DataServiceUri + "/" + subscription.id + "/datasets?includeCandidates=" + v,
}))
.done((result: { continuationToken; results }) => {
console.log(["Result from DataSet Api", result]);
var data = result.results;
mapper.fromJS(data, {}, this.dataSets);
}).always(() => {
this.isContentLoading(false);
xhr = null;
});
});
答案 0 :(得分:1)
在调用ko.mapping
之前合并数据。
jQuery.when
可以等待多个延迟(ajax)对象。
http://api.jquery.com/jquery.when/
在这里,我们必须使用apply
技巧将ajax
个对象传递给$.when
,因为我们正在处理未知的ajax调用计数。
//map your data array into an array of deferred objects, feed to $.when
$.when.apply($, $.map(userStore.get().subscriptions(), function(subscription) {
return $.ajax(..); //without any 'done' 'always' 'fail' callbacks!
})).done(function() {
//count of result is unknown, have to get them out from arguments
$.each(arguments, function(i, arg) {
// arg[0] is the JSON data, arg[1] and arg[2] are statusText, jqXHR.
});
// now, you got all JSON data, merge them before ko.mapping :-)
});