如何将所有observable重置为默认值

时间:2016-07-10 19:53:31

标签: javascript knockout.js knockout-3.0

我有几个可观察的属性。我不想重置单个可观察属性。这是我的一些示例代码。

function viewData() {
     var self = this;
     self.Id = ko.observable("");
     self.Name = ko.observable("");
     self.Display = ko.observable("");
     self.Date = ko.observable("");

     self.Reset = function {
          //Reset all observable variables here
     }
}

这是真实的简短列表。我有大约30个可观察的属性。

2 个答案:

答案 0 :(得分:1)

不确定这是否是您所需要的,但您可以将设置默认值提取到函数中,并在需要重置所有值时使用它

function viewData() {
    setDefaultValues()

    self.Reset = function {
        setDefaultValues()
    }
}

var setDefaultValues = function () {
    var self = this;
    self.Id = ko.observable("");
    self.Name = ko.observable("");
    self.Display = ko.observable("");
    self.Date = ko.observable("");
}

答案 1 :(得分:1)

如果你想要清除" observables,使用ko.isWriteableObservable(...)实用程序方法:



function viewData() {
  var self = this;
  self.Id = ko.observable("A");
  self.Name = ko.observable("B");
  self.Display = ko.observable("C");
  self.Date = ko.observable("D");

  self.Reset = function() {
    for (var key in self) {
      if (self.hasOwnProperty(key) && ko.isWriteableObservable(self[key])) {
        self[key](null);
      }
    }
  };
}

ko.applyBindings(new viewData());

pre { font: 11px consolas; padding: 5px; background: #fafafa; border: 1px solid #ddd; }

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>

<input data-bind="textInput: Id"><br>
<input data-bind="textInput: Name"><br>
<input data-bind="textInput: Display"><br>
<input data-bind="textInput: Date"><br>
<button data-bind="click: Reset">Reset</button>
<hr>Debug info: <pre data-bind="text: ko.toJSON($root, null, 2)"></pre>
&#13;
&#13;
&#13;

如果您确实要设置默认值,则必须手动实现该模式。对于您的答案给出的用例,the answer by @Nora将正常工作。对于更复杂的场景,您需要定义&#34;定义&#34;你的默认值是某种方式:

&#13;
&#13;
function viewData() {
  var self = this;
  
  var defaults = {
    Id: 0,
    Name: "",
    Display: "stub value",
    Date: new Date()
  };
  
  self.Id = ko.observable();
  self.Name = ko.observable();
  self.Display = ko.observable();
  self.Date = ko.observable();

  self.Reset = function() {
    for (var key in self) {
      if (self.hasOwnProperty(key) && ko.isWriteableObservable(self[key])) {
        self[key](defaults[key]);
      }
    }
  };
  
  self.Reset();
}

ko.applyBindings(new viewData());
&#13;
pre { font: 11px consolas; padding: 5px; background: #fafafa; border: 1px solid #ddd; }
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>

<input data-bind="textInput: Id"><br>
<input data-bind="textInput: Name"><br>
<input data-bind="textInput: Display"><br>
<input data-bind="textInput: Date"><br>
<button data-bind="click: Reset">Reset</button>
<hr>Debug info: <pre data-bind="text: ko.toJSON($root, null, 2)"></pre>
&#13;
&#13;
&#13;