Javascript 根据可观察到的变化刷新ViewModel
例如,我有以下型号:Javascript 根据可观察到的变化刷新ViewModel,javascript,mvvm,knockout.js,Javascript,Mvvm,Knockout.js,例如,我有以下型号: var Volume = function (id, path, isactive) { var self = this; self.id = ko.observable(id); self.path = ko.observable(path); self.isactive = ko.observable(isactive); self.Save = function (data) {
var Volume = function (id, path, isactive) {
var self = this;
self.id = ko.observable(id);
self.path = ko.observable(path);
self.isactive = ko.observable(isactive);
self.Save = function (data) {
//ajax post
}
self.Update = function (data) {
//ajax post
}
}
var ViewModel = function (data) {
var self = this;
self.volumes = ko.observableArray(data.volumes.map(function (item) {
return new Volume(item.id, item.path, item.isActive, item.description);
}));
self.AddVolume = function () {
self.volumes.push(new Volume());
}
}
保存或更新后,我想从卷模型中刷新父视图模型,因为数据库中的某些值已更改
如何重新初始化ViewModel
var viewModel = new ViewModel(ko.utils.parseJson(data) || []);
ko.applyBindings(viewModel);
我认为您不需要刷新父vm,如果需要,您可以在更新后从值更改数组的特定索引。或者在清除数组中的旧值后调用getall方法并推送所有值(但不建议这样做)。或者你可以刷新页面。明智地选择您可以在父模型中使用一个函数来加载新数据并填充新数据。然后,在需要获取新数据的任何地方,只需调用该函数即可 例如:
var Volume = function (data) {
var self = this;
self.id = ko.observable(data.id);
self.path = ko.observable(data.path);
self.isactive = ko.observable(data.isactive);
self.Save = function (data) {
//ajax post
//whenever you want to load data again you call viewModel.Load();
}
self.Update = function (data) {
//ajax post
//whenever you want to load data again you call viewModel.Load();
}
}
var ViewModel = function () {
var self = this;
self.volumes = ko.observableArray();
self.Load = function (){
//your ajax call or whatever you do to get the data
self.volumes($.map(data.volumes, function (item) {
return new Volume(item);
}
}
self.AddVolume = function () {
obj = {id:"",path:"",isactive:false}
// need to pass data to Volume model
self.volumes.push(new Volume(obj));
}
}
var viewModel = new ViewModel();
viewModel.Load();
ko.applyBindings(viewModel);
我建议您在父模型中使用
save
和update
函数,并使用$parent
数组对象来引用 刷新父视图模型是什么意思?将新数据绑定到视图模型是否在Save
和update
ajax回调中更新当前的Volume
?当前卷和数组中的其他卷也会受到影响,这就是为什么我要刷新屏幕。如果没有完整的代码,我想说,您可以在创建卷时将视图模型
交给卷
,然后简单地调用刷新
方法。