【问题标题】:Refresh ViewModel on observable change在可观察到的变化上刷新 ViewModel
【发布时间】:2017-09-29 17:19:54
【问题描述】:

例如我有以下模型:

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());
        }
    }

保存或更新后,我想从 Volume 模型中刷新父 ViewModel,因为数据库中的某些值已更改。

如何重新初始化 ViewModel?

var viewModel = new ViewModel(ko.utils.parseJson(data) || []);
ko.applyBindings(viewModel);

【问题讨论】:

  • 刷新父 ViewModel 是什么意思?
  • 将新数据绑定到 ViewModel
  • 您是否在SaveUpdate ajax 回调中更新您当前的Volume
  • 当前卷和阵列中的其他卷也受到影响,这就是我要刷新屏幕的原因。
  • 如果没有完整的代码,我想说您可以在创建时将您的ViewModel 提供给您的Volume,并在其上调用Refresh 方法。

标签: javascript mvvm knockout.js


【解决方案1】:

你可以在你的父模型中有一个函数来加载新数据并填充新数据。然后在任何需要获取新数据的地方,只需调用该函数即可。

例子:

   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);

我建议您在父模型中使用 saveupdate 函数,并使用 $parent 数组对象来引用。

【讨论】:

    【解决方案2】:

    我认为您不需要刷新父虚拟机,如果需要,您可以从更新后的值更改数组的特定索引。或者在清除数组中的旧值后调用getall方法,将所有值推送(但不推荐)。或者您可以刷新页面。明智地选择

    【讨论】:

      猜你喜欢
      • 2019-03-19
      • 2020-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-30
      • 1970-01-01
      相关资源
      最近更新 更多