我正在努力理解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;
}对于给定的topic,我有一个或多个query实例。每个查询都包含一个posting实例列表。每个posting引用一个文档。多个posting可以引用给定的document,只要posting实例属于不同的query实例。
如果posting引用了一个新文档(还没有被任何query检索),我希望创建一个新实例;如果document已经存在( it是唯一的),我想重用它。
我可以看到一些用于构造服务器返回的JSON数据的可能的替代方案:
序列化数据的合理模式是什么?有什么映射插件魔术可以简洁地表达这一点吗?我可以控制生成JSON的服务器,并且可以以任何有意义的方式构造它。
谢谢,
基因
发布于 2012-01-19 20:08:16
下面是我为实现选项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查找现有实例。
发布于 2012-01-19 04:39:11
签出entityspaces.js,您可以观看一个视频,它支持完整的层次数据模型,甚至会生成您的WCF服务,它也支持REST。
使用Knockout的Javascript ORM (数据访问)框架
https://stackoverflow.com/questions/8372324
复制相似问题