【问题标题】:Clearing out data from knockout observable从可观察到的淘汰赛中清除数据
【发布时间】:2016-10-14 05:43:03
【问题描述】:

我有以下型号

self.newItem = ko.observable({
    manufacturer: ko.observable(),
    itemnumber: ko.observable(),
    itemDescription: ko.observable(),
    priceclass: ko.observable(),
    currentPrice: ko.computed(function () {
        return "1.22";
    }, this),
    aeAuthority: ko.computed(function () {
        return "1.02PC";
    }, this),
    requestedMinimumQuantity: ko.computed(function () {
        return "!.22 PC";
    }, this),
    RequestedPrice: ko.observable(),
    ExpirationDate: ko.observable(),       
    ItemDetails: ko.observable(),
    Margin: ko.observable(),
    Status: ko.observable()

});

我想清除此 observable 中的数据,但是当我执行 self.newItem = ""; or self.newItem(''); 时,它会删除 newItem 中的所有 observable,因此 newItem 中没有任何属性。我可以进入并单独清除 newItem 中的每个可观察对象,但有没有更好的方法。

谢谢

【问题讨论】:

  • 您是在问如何从新项目中删除所有项目,然后放入一个空项目以便他们可以更新它??
  • 定义“清除”。此外,请描述您尝试实现的功能。您很可能正在尝试以不同的方式更好地解决问题。
  • 清除我的意思是让 newItem 中的所有 observables 都为空,例如制造商 = ''。我将它映射到模态对话表单中,因此当表单关闭时,我想清空新项目,以便映射到制造商或项目编号等数据的所有字段都变为空。
  • 当你需要一个新的模式时,为什么不简单地生成一个新的视图模型呢?这将是在淘汰赛中做到这一点的方法。比编写额外代码来重置现有视图模型要容易得多。但是你当然可以结合 ko.utils.objectForEach()ko.isWritableObservable() 来创建一个循环,覆盖任意对象的所有可观察属性。

标签: knockout.js


【解决方案1】:

Knockout 中没有迭代 方法,您必须自己编写一个。通常我建议使用构造函数,其中有很多选项可供您选择(具体实现取决于要求)。

但是,要“直接”回答您的问题,这是“清除”另一个可观察对象中可观察属性中所有数据的最简单方法:

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

这是一个可运行的示例:

function ViewModel() {
  var self = this;
  
  self.newItem = ko.observable({
    manufacturer: ko.observable("Some manufacturer"),
    itemnumber: ko.observable("12345"),
    itemDescription: ko.observable("A nice item"),
    priceclass: ko.observable("High"),
    currentPrice: ko.computed(function () {
        return "1.22";
    }, this),
    aeAuthority: ko.computed(function () {
        return "1.02PC";
    }, this),
    requestedMinimumQuantity: ko.computed(function () {
        return "!.22 PC";
    }, this),
    RequestedPrice: ko.observable(1.25),
    ExpirationDate: ko.observable(new Date()),       
    ItemDetails: ko.observable("Comes with a thingie"),
    Margin: ko.observable(0.25),
    Status: ko.observable("Available")
  });
  
  self.clean = function() {
    var item = self.newItem();
    for (var key in item) {
      if (item.hasOwnProperty(key) && ko.isWriteableObservable(item[key])) {
        item[key](null);
      }
    }
  };
}

ko.applyBindings(new ViewModel());
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>
<button data-bind="click: clean">clean out everything</button>
<pre data-bind="text: ko.toJSON($root, null, 2)"></pre>

【讨论】:

    【解决方案2】:

    这是另一种清除模型的好方法。在ko.simpleMap 的帮助下,您可以使用默认值为 viewModel 中的现有模型分配一个新值。它使用Array functionsome。您也可以在从服务器获取数据然后将值应用于现有视图模型的场景中使用它。您也可以将ko.simpleMap 用于JS 对象作为source

    (function(){
        ko.simpleMap = function(source, target, excludedFields){
            excludedFields = excludedFields || [];
    
            for(var key in source){
                if(!source.hasOwnProperty(key) || key[0] === "_" || excludedFields.some(function(excludedField) {
                    return excludedField.toLowerCase() === key.toLowerCase();
                }))
                    continue;
                var targetKey;
                if(!Object.getOwnPropertyNames(target).some(function(tempKey) {
                    if(tempKey.toLowerCase() === key.toLowerCase()){
                        targetKey = tempKey;
                        return true;
                    }
    
                    return false;
                }))
                    continue;
    
                var sourceValue;
    
                if(typeof source[key] === "function")
                    sourceValue = source[key]();
                else
                    sourceValue = source[key];
    
                if(typeof target[targetKey] === "function"){
                    if(ko.isWriteableObservable(target[targetKey]))
                        target[targetKey](sourceValue);
                } else
                    target[targetKey] = sourceValue;
            }
    
            return target;
        };
    
    })();
    
    function MyModel(){
        this.manufacturer= ko.observable();
        this.itemnumber= ko.observable();
        this.itemDescription= ko.observable();
        this.priceclass= ko.observable();
        this.currentPrice= ko.computed(function () {
            return "1.22";
        }, this);
        this.aeAuthority= ko.computed(function () {
            return "1.02PC";
        }, this);
        this.requestedMinimumQuantity= ko.computed(function () {
            return "!.22 PC";
        }, this);
        this.RequestedPrice= ko.observable();
        this.ExpirationDate= ko.observable();       
        this.ItemDetails= ko.observable();
        this.Margin= ko.observable();
        this.Status= ko.observable("Approved");
    
    }
    
    var viewModel = {
      item: new MyModel(),
      clear: function(){
        ko.simpleMap(new MyModel(), this.item);
      }
    };
    
    ko.applyBindings(viewModel);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
    
    <input data-bind="value: item.manufacturer" type="text" /><span data-bind="text: item.manufacturer"></span><br/>
    <input data-bind="value: item.itemnumber" type="text" /><span data-bind="text: item.itemnumber"></span><br/>
    <input data-bind="value: item.itemDescription" type="text" /><span data-bind="text: item.itemDescription"></span><br/>
    <input data-bind="value: item.priceclass" type="text" /><span data-bind="text: item.priceclass"></span><br/>
    <span data-bind="text: item.currentPrice"></span><br/>
    <span data-bind="text: item.aeAuthority"></span><br/>
    <span data-bind="text: item.requestedMinimumQuantity"></span><br/>
    <input data-bind="value: item.RequestedPrice" type="text" /><span data-bind="text: item.RequestedPrice"></span><br/>
    <input data-bind="value: item.ExpirationDate" type="text" /><span data-bind="text: item.ExpirationDate"></span><br/>
    <input data-bind="value: item.ItemDetails" type="text" /><span data-bind="text: item.ItemDetails"></span><br/>
    <input data-bind="value: item.Margin" type="text" /><span data-bind="text: item.Margin"></span><br/>
    <input data-bind="value: item.Status" type="text" /><span data-bind="text: item.Status"></span><br/>
    <button data-bind="click:clear">Clear</button><br/>

    【讨论】:

      猜你喜欢
      • 2015-03-20
      • 2012-12-02
      • 2012-09-08
      • 2013-06-02
      • 2015-10-05
      • 2023-03-11
      • 2014-11-05
      • 2012-07-07
      相关资源
      最近更新 更多