Javascript 如何完全清空具有可观察属性的可观察对象?

Javascript 如何完全清空具有可观察属性的可观察对象?,javascript,knockout.js,Javascript,Knockout.js,我有两个这样的物体 self.objCurrentResource = ko.observable({ UID: ko.observable(), Capacity: ko.observable(), Duration: ko.observable(), Name: ko.observable(), Description: ko.observable(), QTY: ko.observable(), //added from wizard

我有两个这样的物体

self.objCurrentResource = ko.observable({
    UID: ko.observable(),
    Capacity: ko.observable(),
    Duration: ko.observable(),
    Name: ko.observable(),
    Description: ko.observable(),
    QTY: ko.observable(), //added from wizard
    SelectedDate: ko.observable(), //added from wizard
    Exeptions: ko.observableArray([]),
    Schedules: ko.observableArray([]),
    ResourceReady: ko.observable(false),
    SelectedSlots: ko.observableArray([])
});
我怎样才能在点击按钮时完全清空所有内容?我有按钮和一切,但我似乎无法清空所有的值。我怎样才能做到这一点呢?

试试这个:

foreach (key in self.objCurrentResource()) self.objCurrentResource()[key](null);

我假设您对清空可观察对象的定义是,将
null
未定义的
写入可观察对象,并将空数组写入
ko.observearray
s

一种方法是: 您的
objCurrentResource
observable返回一个javascript对象。您必须迭代它的属性,并对每个值执行某种
clear
方法。因此:

  • 检索对象
  • 迭代其值
  • 清除每个值
  • var clearIfObservable=函数(值){
    如果(!ko.isoservable(value))返回;
    //快速检测可见光的方法:
    // //https://github.com/knockout/knockout/pull/706#issuecomment-33545542
    如果('push'输入值){
    价值([]);
    }否则{
    //常规obs.案例:
    值(未定义);
    }
    };
    var clearAllObservableProperties=函数(obj){
    Object.keys(obj.forEach)(函数(k){
    clearIfObservable(obj[k])
    });
    返回obj;
    };
    var objCurrentResource=ko.可观测({
    UID:ko.observable(),
    容量:ko.可观察(),
    持续时间:ko.可观察(),
    名称:ko.observable(),
    Description:ko.observable(),
    数量:可观察到的数量(),
    SelectedDate:ko.observable(),
    例外情况:ko.observableArray([]),
    附表:ko.observableArray([]),
    ResourceReady:ko.可观察(假),
    所选插槽:ko.observableArray([])
    });
    log(“在ResourceReady值之前:”,objCurrentResource().ResourceReady());
    log(“在计划值之前:”,objCurrentResource().Schedules());
    clearAllObservableProperties(objCurrentResource());
    log(“在ResourceReady值之后:”,objCurrentResource().ResourceReady());
    log(“在调度值之后:”,objCurrentResource().Schedules())
    
    尝试self.objCurrentResource(空);我做了,但它不起作用。如果你能为它制作一些小提琴,那就太好了。
    var clearIfObservable = function(value) {
      if (!ko.isObservable(value)) return;
    
      // Quick way of detecting observableArray: 
      // //https://github.com/knockout/knockout/pull/706#issuecomment-33545542
      if ('push' in value) { 
        value([]);
      } else {
        // Regular obs. case:
        value(undefined);
      }
    };
    
    var clearAllObservableProperties = function(obj) {
      Object.keys(obj).forEach(function(k) {
        clearIfObservable(obj[k])
      });
    
      return obj;
    };