0

我知道 toJSON 可以被覆盖,如此处所述,但是否可以提供自定义 toJS 函数?

4

1 回答 1

0

是的,这就像编写一个新函数一样简单。

但是,更好的选择是在ko.toJSON.

ko.ToJSON(vm, white-list, spacing).

HTML

<pre data-bind="text: ko.toJSON($root, replacer, 2)"></pre>

JS

var ViewModel = function() {
   var self = this;

   self.name = ko.observable();
   self.age = ko.observable();
   self.canEatLotsOfPizza = ko.observable();
   self.sawTheNewStarTrekMovie = ko.observable();
   self.watchesWheelOfFortune  = ko.observable();

   self.replacer = function(key, value) {
      if(!key) {
         delete value.canEatLotsOfPizza;
         delete value.sawTheNewStarTrekMovie; 
         delete value.watchesWheelOfFortune ; 
      }

      return value;
   };
};

ko.applyBindings(new ViewModel());
于 2013-06-12T15:35:59.387 回答