2011-12-04 20 views
2

我想了解KnockoutJS是否適用於我的應用程序。我的數據模型(簡化的)是如下: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實例屬於不同的query實例,多於一個posting可以指代給定的document

如果一個posting引用了一個新文檔(其中一個還沒有被任何query檢索到),我想創建一個新實例;如果document已經存在(id是唯一的),我想重新使用它。

我可以看到一些可能的替代方案以構建由服務器返回的JSON數據:

  1. 當序列化的貼子,第一序列的所有文件的清單,並與他們更新主文檔列表。然後,發送帶有文檔ID參考的帖子。
  2. 將每個文檔完全序列化爲發佈的屬性,然後確定該條目是否多餘。將非冗餘條目添加到主列表中。

什麼是序列化數據的合理模式?有沒有一些映射插件魔術可以簡潔表達?我可以控制生成JSON的服務器,並且可以以任何有意義的方式構建它。

感謝,

基因

+0

基因,這個問題是相當寬泛和主觀的。我不清楚我們可以客觀回答哪些具體問題。 –

+0

那麼,我一直在尋找最佳實踐方面的成語指導。我實施了戰略#1,因爲我可以控制服務器。 –

回答

1

這裏就是我清盤做來實現選項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查找現有的實例。

0

結帳entityspaces.js,有一個視頻,你可以看,它完全支持hierarchcial數據模型,甚至會產生你的WCF JSON的服務,它支持REST API的爲好。

一個JavaScript ORM(數據訪問)的框架,採用淘汰賽

https://github.com/EntitySpaces/entityspaces.js#readme

+1

我是否說你創作了EntitySpaces?如果是這樣,請指出你做了(並且爲你的其他答案也這樣做)。請閱讀有關此問題的常見問題解答:http://stackoverflow.com/faq#promotion – Bart

+0

對不起,我不知道這一點,並感謝您的鏈接。是的,我自己,David和Scott是EntitySpaces的創造者。 –