我有很多(KnockOut)视图模型,这些视图模型都是从rest服务获取数据,然后填充非常简单的“ item”视图模型,并且只包含来自REST接口的字段。
我只是想知道是否有一种方法不必定义项目视图模型,而是以某种方式将它们动态创建为对象(每个属性都是可观察的)。
因此,在下面的示例中,我不希望拥有“ ItemViewModel”,而只是在AddItems函数中说,它应该基于数据创建一个对象,并使每个条目成为ko.observable。然后,传递的“ itemName”包含“ ItemViewModel1”(或在其他调用中为“ ItemViewModel2” ... etc)。
所以例如如果Json Rest输入的字段为“ LAST_NAME”,则会添加self.LAST_NAME = ko.observable()”,并填充该值等(因此,我仍然可以在视图中引用它)。
var ItemViewModel1 = function (data) {
var self = this;
self.PAR1 = ko.observable(data.PAR1)
self.PAR2 = ko.observable(data.PAR2)
self.PAR3 = ko.observable(data.PAR3)
self.PAR4 = ko.observable(data.PAR4)
// … etc
}
var MasterViewModel1 = function (data) {
var self = this;
ReportBaseViewModel.call(self)
}
var ReportBaseViewModel = function () {
var self = this;
/* commonly used vars */
self.report = ko.observable();
self.searchedCallBackFunction = ko.observable();
self.items = ko.observableArray();
self.selecteditem = ko.observable();
self.selectedPerson = ko.observable();
/* method: print */
self.PrintEventHandler = function (data) { window.print(); };
/* method: add items to array */
self.AddItems = function (data) {
var newitems = ko.utils.arrayMap(data, function (item) {
c = new window[self.itemname](item);
return c;
});
self.items(newitems);
};
/* eventhandler: select one item */
self.SelectEventHandler = function (item) {
selecteditem(item);
};
self.GetReport = function (selectedPerson, viewContainer, url, itemName) {
self.selectedPerson(selectedPerson);
self.itemname = itemName;
var jqxhr = $.ajax({
url: url,
type: "GET"
}).done(function (data, textStatus, jqXHR) {
if (data != null) {
self.AddItems(data);
$('#' + viewContainer).show();
document.getElementById(viewContainer).scrollIntoView();
}
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log('fail' + JSON.stringify(jqXHR));
toastr.options = {
"closeButton": true,
"debug": false,
"newestOnTop": false,
"progressBar": false,
"positionClass": "toast-top-right",
"preventDuplicates": false,
"onclick": null,
"showDuration": "0",
"hideDuration": "1000",
"timeOut": "0",
"extendedTimeOut": "0",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
};
toastr["error"]("ERROR");
}).always(function (jqXHR, textStatus, errorString) {
if (typeof self.searchedCallBackFunction() === 'function') {
self.searchedCallBackFunction();
}
});
}
}
最佳答案
有。如果您的对象很简单并且没有嵌套,则可以编写代码自己映射它们:
var someJSON = '{ "firstName": "John", "lastName": "Doe" }';
var makeSimpleVM = function(obj) {
// Return a new object with all property
// values wrapped in an observable
return Object
.keys(obj)
.reduce(function(vm, key) {
vm[key] = ko.observable(obj[key]);
return vm;
}, {});
};
var myVM = makeSimpleVM(JSON.parse(someJSON));
console.log(ko.isObservable(myVM.firstName)); // true
console.log(myVM.firstName()); // John
myVM.firstName("Jane");
console.log(myVM.firstName()); // Jane
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
我认为通读这个简单的实现很重要:它使您理解为什么使用现成的插件可能是一个更好的主意。
一旦服务器端代码包含数组,嵌套的视图模型或您不希望映射的任何属性,就会遇到问题。
ko.mapping
插件已经为您解决了这些问题。它将数组映射到ko.observableArray
,并允许您指定映射策略。var someJSON = '{ "firstName": "John", "lastName": "Doe" }';
// Let's use the library this time
var myVM = ko.mapping.fromJS(JSON.parse(someJSON));
console.log(ko.isObservable(myVM.firstName)); // true
console.log(myVM.firstName()); // John
myVM.firstName("Jane");
console.log(myVM.firstName()); // Jane
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js"></script>