仅从 Knockout ViewModel 复制可写项目

copy only writable items from Knockout ViewModel

我的 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] 没有 return Observable 变量。

您必须获取 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>