3

我在 Knockout 视图模型中有一个数组,如下所示:

this.Activities = ko.observableArray([
{ "date": "28/11/2012 00:00:00",
  "activities": [
     { "company": "BOW",
       "description": "Backup Checks",
       "length": "60"
     },
     { "company": "AMS",
       "description": "Data Request",
       "length": "135"
     },
  ]},
{ "date": "30/11/2012 00:00:00",
  "activities": [
     { "company": "BOW",
       "description": "Backup Checks",
       "length": "60"
     },
     { "company": "SLGT",
       "description": "Software Development",
       "length": "240"
     },
     { "company": "BOW",
       "description": "Data Request",
       "length": "30"
     },
  ]},
]);

我使用此代码向其中添加一个新元素:

this.Activities.push(new NewActivity(company, description, length, fullDate));

其中使用 NewActivity 功能:

function NewActivity(company, description, length, date) {
    this.date = date;
    this.activities = [{ "company": company, "description": description, "length": length }];
}

它工作正常。但是,它每次被释放时都会创建一个全新的对象。当代码检查已创建对象的日期时,我需要实现一个条件。如果新创建的对象具有相同的日期,则应将活动详细信息添加到该日期的活动数组中的活动数组中。

我该怎么做?

活动数组的所有数据都来自 MVC 应用程序中强类型视图中的模型:

this.Activities = ko.observableArray([
        @foreach (ActivitySet aSet in Model)
        {
            @:{ "date": "@aSet.Date",
            @:"activities": [
                 foreach(Activity a in aSet.Activities)
                 {
                     @:{ "company": "@a.Companies.Select(c => c.Title).Single()",
                       @:"description": "@a.Descriptions.Select(c => c.Title).Single()",
                       @:"length": "@a.LengthInMinutes"
                     @:},
                 }
            @:]},
        }
]);
4

1 回答 1

4

我建议您创建一些实体来描述您的活动:

// Details
function ActivityDetails(company, description, length) {
    this.company = ko.observable(company);
    this.description = ko.observable(description);
    this.length = ko.observable(length);
}

// Activity
function Activity(date, activityDetails) {
    this.date = ko.observable(date);
    this.details = ko.observableArray(activityDetails);
}

您可以通过以下方式控制活动:

function ViewModel () {
    var self = this;

    this.Activities = ko.observableArray([
        // Activities here
    ]);

    this.addActivity = function (activity) {
        var flag = false;
        ko.utils.arrayMap(self.Activities(), function (item) {
            // Flag is here so it doesn't keep checking further in iterations
            if (!flag) {
                if (item.date() === activity.date()) {
                    item.details.push(activity.details);
                    flag = true;
                }
            }
        });
        // Case where activity date was not found in existing records
        if (!flag) {
            self.Activities.push(activity);
        }
    }
}

这要求您的视图模型具有我提供的示例的自定义添加方法。请注意,我在任何地方都在解析可观察值,因此如果您使用不可观察值,请删除函数调用。

于 2012-11-30T12:57:21.587 回答