2013-08-25 40 views
0

我試圖從一個json文件解析數據到一個集合視圖,該文件對每個數據組都有數字鍵。該JSON看起來是這樣的:Backbone Js - 解析數據問題

{ 
    "0": { 
     "artifact_id": "36", 
     "timestamp": "2013-08-20 11:59:00", 
     "modified": "2013-08-20 11:59:00", 
     "text": "Why did the last one duplicate? I don't think I clicked it twice...", 
     "author_desc": "", 
     "object_type": "artifact", 
     "comments": [] 
    }, 
    "1": { 
     "artifact_id": "35", 
     "timestamp": "2013-08-20 11:57:51", 
     "modified": "2013-08-20 11:57:51", 
     "text": "This is a new artifact for a new day.", 
     "author_desc": "", 
     "object_type": "artifact", 
     "comments": [] 
    }, 
    "2": { 
     "artifact_id": "34", 
     "timestamp": "2013-08-20 11:57:50", 
     "modified": "2013-08-20 11:57:50", 
     "text": "This is a new artifact for a new day.", 
     "author_desc": "", 
     "object_type": "artifact", 
     "comments": [] 
    } 
} 

我怎樣寫一個模型解析採取的條目(0,1,2 ...等),從數據中的每個模型的每一個?

這是我收集,從下面凱西建議此外,但它似乎並沒有被運行的解析方法:

var FriendCollection = Backbone.Collection.extend({ 
    model: FriendModel, 
    parse: function(data) { 
     console.log('running parse'); 
     return _.map(data, _.identity); 
    } 
}); 
var friendCollection = new FriendCollection(); 
friendCollection.reset(friendjson); 
+0

collection.parse僅在從服務器進行提取時運行。 http://backbonejs.org/#Collection-parse –

回答

2

Collection#reset不叫parse,有沒有辦法讓它調用parse。您有幾種選擇:

  1. 轉換friendjson到一個數組的手,給reset數組。
  2. 完全不需要reset,只需將friendjson傳遞給集合的構造函數,幷包含{parse: true} option
  3. 用您自己的版本替換您的收藏品reset,如果您包含{parse: true}選項,請撥打parse

應該很明顯。

應該是這樣的:

var friendCollection = new FriendCollection(friendjson, { parse: true }); 

演示:http://jsfiddle.net/ambiguous/dbM82/

會是這個樣子:

var FriendCollection = Backbone.Collection.extend({ 
    //... 
    reset: function(models, options) { 
     if(options && options.parse) { 
      delete options.parse; 
      models = this.parse(models); 
     } 
     return Backbone.Collection.prototype.reset.call(this, models, options); 
    } 
}); 

var friendCollection = new FriendCollection(); 
friendCollection.reset(friendjson, { parse: true }); 

演示:http://jsfiddle.net/ambiguous/Rs8es/

+0

謝謝@mu太短了,就這樣做了。感謝您的詳細解釋。 – flashpunk

+0

或者,如果這是一個特殊的情況,你可以直接調用解析函數:'friendCollection.reset(friendCollection.parse(friendjson))' – mnoble01

0

使用Collection#parse方法。

var MyCollection = Backbone.Collection.extend({ 
    parse: function (data) { 
    return _.map(data, _.identity); 
    } 
}); 
+0

謝謝@Casey Foster,雖然似乎沒有工作。解析方法似乎沒有被調用。我已將集合代碼添加到上面的原始帖子中。 – flashpunk

+0

我以爲你調用'fetch'來獲取這些數據。由於您使用'reset',因此您需要傳遞'parse:true'選項。 'friendCollection.reset(friendjson,{parse:true});' –

+0

我想能夠使用提取選項,但我似乎無法讓它運行......我正在努力工作它首先通過這種方式使用數據。 無論哪種方式,運行friendCollection.length仍然只能返回1不幸的。 – flashpunk