【问题标题】:Field-level change tracking with ASP.NET MVC4 & Knockout使用 ASP.NET MVC4 和 Knockout 进行字段级更改跟踪
【发布时间】:2012-11-06 17:50:40
【问题描述】:

想知道是否有人有跟踪字段级更改跟踪的经验?我们正在尝试找出最简单/最好的方法来跟踪最终用户的任何和所有模型修改。我正在使用 ASP.NET MVC4、Knockout 和 Knockout Editables。

更新: 由于跟踪功能的要求,仅检测对象是否脏是不够的,因为我需要确定发生了什么变化以及值。我选择使用 for 循环来迭代模型属性,使用 KO Editables.hasChanges() 函数检测更改,并使用当前值和 .oldValue()(KO Editable)构建自定义日志对象。

【问题讨论】:

    标签: asp.net-mvc knockout.js knockout-mvc kolite


    【解决方案1】:

    既然您提到想要使用 KnockoutJS 实现更改跟踪的最简单和最好的方法,我建议您看看 John Papa 最近在 Pluralsight 的单页应用程序课程中实施的内容。您可以阅读他关于更改跟踪的博文(底部链接)了解更多信息。

    它的要点是:他与 Hans Fjällemark 一起,在 Steve Sanderson(KnockoutJS 的创建者)和 Ryan Niemeyer(KnockoutJS 的核心贡献者)的提示下,创建了一个自定义更改跟踪工具 DirtyFlag。 DirtyFlag 作为 KoLite 库的一部分提供,可以从 github 或 NuGet:Install-Package KoLite 下载。

    博客文章包含启动和运行所需的所有步骤:

    http://www.johnpapa.net/spapost10/

    【讨论】:

    • 这是一篇关于检测“脏”记录的好帖子,但我正在寻找一种方法来了解 LastName 是否从“Smith”更改为“Smiths”。我选择了对模型进行快速 for 循环,并使用 KO Editables .hasChanges() 方法来构建自定义日志。谢谢你的链接!
    【解决方案2】:

    这是一篇 Ryan Niemeyer 实现此类功能的文章:http://www.knockmeout.net/2011/05/creating-smart-dirty-flag-in-knockoutjs.html

    【讨论】:

      【解决方案3】:

      还有另一种解决方法,我会按照以下方式实施

      var self = this;
      
      // Following property is binded with you to indicate has changes
      self.hasChanges = ko.observable(false); 
      
      // Following is the customer object and we want its field tracking
      self.customer = ko.observable();
      
      self.initializeCustomer = function (customer) {
      
          // Following loop read all the properties from customer object
          var properties = [];
          for (var prop in customer)
          {
              if(customer.hasOwnProperty(prop) && typeof customer[prop] !== 'function')
              {
                  properties.push(prop);
              }
          }
          //following loop create new observable properties on trackingCustomer object and 
          // subscribe their event
          var trackingCustomer = {};
          for (var prop in properties)
          {
              trackingCustomer[properties[prop]] = ko.observable(properties[prop]);
              trackingCustomer[properties[prop]].subscribe(function (newvalue)
              {
                  self.hasChanges(true);
              }
              );
          }
      
          self.customer(trackingCustomer);
      };
      

      【讨论】:

        【解决方案4】:

        由于跟踪功能的要求,仅检测对象是否脏是不够的。我选择使用 for 循环来迭代模型属性,使用 KO Editables .hasChanges() 函数检测更改,并使用当前值和 .oldValue() (KO Editable) 构建自定义日志对象。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-01-18
          • 2013-02-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-06-02
          相关资源
          最近更新 更多