gpt4 book ai didi

javascript - knockoutjs 的数据加载模式

转载 作者:行者123 更新时间:2023-11-30 06:01:17 25 4
gpt4 key购买 nike

我正在尝试了解 KnockoutJS 是否适用于我的应用程序。我的数据模型(简化)如下:

function topic(data) {
this.id = data.id;
this.queries = ko.observableArray([]);
}

function query(data) {
this.id = data.id;
this.text = data.text;
this.searcher = data.searcherId;
this.postings = ko.observableArray([]);
}

function posting(data, query) {
this.documentId = data.docid;
this.rank = data.rank;
this.snippet = data.snippet;
this.score = data.score;
this.query = query;
this.document = null;
}

function document(data, topic) {
this.id = data.id;
this.url = data.url;
this.topic = topic;
}

对于给定的主题,我有一个或多个query 实例。每个查询都包含一个 posting 实例列表。每个 posting 都指向一个文档。多个 posting 可以引用给定的 document,只要 posting 实例属于不同的 query 实例。

如果 posting 引用了一个新文档(一个尚未被任何 query 检索到的文档),我想创建一个新实例;如果 document 已经存在(id 是唯一的),我想重新使用它。

我可以看到一些可能的替代方案来构造服务器返回的 JSON 数据:

  1. 序列化过帐时,首先序列化所有文档的列表,并用它们更新主文档列表。然后,发送包含对文档 ID 的引用的帖子。
  2. 将每个文档完全序列化为帖子的属性,然后找出该条目是否多余。将非冗余条目添加到主列表。

序列化数据的合理模式是什么?是否有一些映射插件魔法可以简洁地表达这一点?我可以控制生成 JSON 的服务器,并且可以以任何有意义的方式构建它。

谢谢,

基因

最佳答案

以下是我为实现选项 1 而做的事情:

function idField(data) {
return ko.utils.unwrapObservable(data.id);
}

function createMapping(type, context) {
return {
key: idField,
create: constructor(type, context)
}
}

function constructor(type, context) {
return function(options) {
return new type(options.data, context);
}
}

function createReferenceMapping(collection) {
return {
key: idField,
create: lookup(collection)
}
}

function lookup(collectionOrClosure) {
return function(options) {
var collection = (typeof collectionOrClosure == 'function') ? collectionOrClosure() : collectionOrClosure;

var object = collection.findById(options.data.idref);
if (object == null)
console.log("Error: Could not find object with id " + options.data.idref + " in ", collection);
return object;
}
}

我这样调用这段代码:

    var mapping = {
people: createMapping(Searcher),
topics: createMapping(Topic, this),
activeTopic: createReferenceMapping(function(){return self.topics();})
};

this.dataChannel.loadModel(function(data) {
ko.mapping.fromJS(data, mapping, this);
}

这需要注意创建新实例(通过 constructor 函数)和通过 lookup 查找现有实例。

关于javascript - knockoutjs 的数据加载模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8372324/

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