سؤال

I'm just wondering how to remove a property from knockout viewModel. Specifically, a computed one. I have a simple viewModel

function viewModel(){
   var self = this;
   self.name = ko.observable("John");
   self.lastname = ko.observable("Doe");
   self.age = ko.observable("22");
   self.fullName = ko.computed(function(){
      return self.name()  + self.lastname();
   });
   self.fullNameAndAge = ko.computed(function(){
      return self.name()  + self.lastname() + ': ' + self.age();
   });
};

The data is going to be sent to the server, but I want to exclude the computed data from the viewModel.

I thought something like this would get all the computed data and remove it, but didn't find anything like it.

      for (observableKey in viewModel) {
        if (ko.isComputed(viewModel[observableKey]) 
                {
            delete viewModel[observableKey];
        }
    }
هل كانت مفيدة؟

المحلول

Knockout can return a regular object from which you then can remove anything you want.

var plainJs = ko.toJS(viewModel);
delete plainJs.fullName;

Documented here.

نصائح أخرى

You can loop through keys like this:

for (var key in obj) {
   if(ko.isComputed(obj[key]))
   {
      delete obj[key];
   }
}

EDIT

Here is a working fiddle.In fiddle click over the button and check the console, there you can see 2 objects, first one is before removing computed obervables and second one is after removing computed observables.

My preferred approach for this sort of problem is to create a specific transport object for whatever your JSON call requires.

var userSaveRequest = function(data) {
  var self = this;
  self.name = data.name;
  self.lastname = data.lastname;
  // etc, etc
}

Then, from my calling code, something like this to get the JSON.

// inside viewModel
self.saveUser = function(){
  var queryData = ko.mapping.toJSON(
    new userSaveRequest(ko.mapping.toJS(self))
  );

  // use querydata in AJAX
}

Also, it's worth remembering just how damn flexible Javascript is. You can create an object of your own design on the fly if need be.

var queryData = ko.mapping.toJSON(
   {
     name: self.name(),
     lastname: self.lastname()
   }
);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top