gpt4 book ai didi

javascript - Knockout.js 更新数组中的数组

转载 作者:行者123 更新时间:2023-11-29 10:20:13 25 4
gpt4 key购买 nike

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

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 }];
}

而且效果很好。但是,它每次被释放时都会创建一个全新的对象。我需要在代码检查已创建对象的日期时实现一个条件。如果新创建的对象具有相同的日期,则应将事件详细信息添加到该日期的 Activities 数组中的 activities 数组。

我该怎么做?

Activities 数组的所有数据都来自 MVC 应用程序中强类型 View 中的模型:

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"
@:},
}
@:]},
}
]);

最佳答案

我建议您创建一些实体来描述您的事件:

// 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);
}
}
}

这需要你的 View 模型有一个自定义的添加方法,我已经提供了一个例子。请注意,我在任何地方都解析可观察值,因此如果您使用不可观察值,请删除函数调用。

关于javascript - Knockout.js 更新数组中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13645547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com