使用ASP.NET MVC4进行字段级更改跟踪&昏死

时间:2012-11-06 17:50:40

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

想知道是否有人有跟踪现场级别更改跟踪的经验?我们正在努力辨别最终用户跟踪任何和所有模型修改的最简单/最佳方式。我正在使用ASP.NET MVC4,Knockout和Knockout Editables。

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

4 个答案:

答案 0 :(得分:8)

由于你提到想要使用KnockoutJS实现更改跟踪的最简单和最好的方法,我建议看看John Papa最近在Pluralsight的单页应用课程中实现了什么。您可以阅读他关于更改跟踪的博客文章(在底部链接)以获取更多信息。

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

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

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

还有另一种解决方法,我会像下面的

那样实现
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);
};

答案 3 :(得分:0)

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