仅从 Knockout ViewModel 复制可写项目

Posted

技术标签:

【中文标题】仅从 Knockout ViewModel 复制可写项目【英文标题】:copy only writable items from Knockout ViewModel 【发布时间】:2019-02-20 13:38:25 【问题描述】:

在我的 ViewModel 中有几个项目包括函数和可观察变量但是在发布时,我只需要可写项目。

var viewModel = 
    firstName: ko.observable().extend( minLength: 2, maxLength: 10 ),
    lastName: ko.observable().extend( required: true ),
    emailAddress: ko.observable(),
    age: ko.observable().extend( min: 1, max: 100 ),
    options: ['News', 'Music'],
    subscription: ko.observable().extend( required: true ),
    password: ko.observable(),
    submit: function () 
        var model = cloneObservable(viewModel);
    ,
    reset: function () 
    
;

ko.applyBindings(viewModel);

克隆视图模型:

 function cloneObservable(viewModel) 
    var model = ko.observableArray([]);
    Object.keys(viewModel).forEach(function (name) 
        if (ko.isWritableObservable(viewModel[name])) 
            model.push(viewModel[name]);
        
    )
    return ko.mapping.fromJS(ko.toJS(model));
 

viewModel[name] 不返回 Observable 变量。

【问题讨论】:

【参考方案1】:

您必须获取 viewModel 的实例并在 CloneObservable 函数中使用它。

我从函数中删除了ko.mapping.fromJS,以说明这些值是正确的。

function cloneObservable(viewModel) 
  var model = ko.observableArray([]);
  Object.keys(viewModel).forEach(function (name) 
      if (ko.isWritableObservable(viewModel[name])) 
          model.push(viewModel[name]);
      
  )
  return ko.toJS(model);



var viewModel = function()
  var self = this;
  self.firstName = ko.observable('sal').extend( minLength: 2, maxLength: 10 );
  self.lastName = ko.observable('mon').extend( required: true );
  self.emailAddress = ko.observable('email');
  self.age = ko.observable(21).extend( min: 1, max: 100 );
  self.options = ['News', 'Music'];
  self.subscription = ko.observable('yes').extend( required: true );
  self.password = ko.observable('secret');
  self.submit = function()
     
  ;
  
;

var viewModelInstance = new viewModel();

ko.applyBindings(viewModelInstance);


console.log(cloneObservable(viewModelInstance));
<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.js"></script>

【讨论】:

以上是关于仅从 Knockout ViewModel 复制可写项目的主要内容,如果未能解决你的问题,请参考以下文章

刷新页面后可以用 Knockout JS 保存 ViewModel 的数据吗?

Knockout.js如何与组件共享viewmodel observable以进行双向绑定

Knockout js绑定可空对象的属性

如何使用 Knockout.js 将多个 View 绑定到单个 ViewModel

Knockout.js:页面或页面的一部分上的多个 ViewModel 绑定

从javascript函数更新Knockout viewmodel表单输入绑定