从Knockout ViewModel复制仅可写项目

时间:2018-09-16 12:14:55

标签: knockout.js knockout-mapping-plugin

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

clone 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 个答案:

答案 0 :(得分: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>