2014-01-14 79 views
2

您好我是新來的骨幹,我只是用了一點玩了,這裏是我的代碼:Backbonejs - 如何打印提取結果?

var Users = Backbone.Collection.extend ({ 
     url : 'http://backbonejs-beginner.herokuapp.com/users' 
    }); 

    var users = new Users(); 
    users.fetch({ 
     success: function() { 
      console.log(users); 
     } 
    }); 

取指令調用成功,我有一個對象,它看起來像返回:

[ 
    { 
    "id": "hqel839m1071rbggsxf7", 
    "firstname": "Thomas", 
    "lastname": "Davis", 
    "age": 12 
    } 
] 

如何打印結果的不同部分? 例如,我想打印第一個項目的「id」參數。我可以像數組一樣迭代它嗎?我試過console.log(users[0].id)但它不起作用。

謝謝。

回答

3

有三種不同的方法可以訪問Backbone.Collection中的模型。首先,您可以使用.get方法根據其唯一標識查找模型。這基本上會查看集合中的所有模型,並將它們的id屬性與提供的屬性進行比較。

var user = collection.get('unique_id'); // return an instance, or null 

第二種方法是使用.at方法按索引獲取模型。如果您的模型已排序,這非常有用。如果它們沒有排序,他們將通過插入要取回(即,它們被提供到集合中的順序排列):

var user = collection.at(0); // return the first model in the collection 

最後,您可以訪問模型的原始陣列集合包裝。您可以通過.models屬性訪問此屬性,該屬性只是一個數組。這不是推薦的方法。

var user = collection.models[0]; 

一旦你有一個用戶,你可以通過.get方法來訪問你的模型的用戶的任何屬性:

var age = user.get("age"); 
user.set("age", 100); 

您可以查看文檔模型get方法here,和文件爲Backbone.Collectionhere

+0

當我嘗試執行console.log(users [0] .get(「id」));我得到「Uncaught TypeError:Can not call method'get'of undefined」 – zeion

+0

對不起,我編輯了我的答案,我忘記了模型數組。我所鏈接的內容現在可以工作。 –

3

不要忘記arguments傳遞給success回調collection.fetch這是(collection, response, options)。檢查文檔here。您可以使用collection參數來選擇特定的model。請查看以下代碼:

var Users = Backbone.Collection.extend ({ 
    url : 'http://backbonejs-beginner.herokuapp.com/users' 
}); 

var users = new Users(); 
users.fetch({ 
    success: function (collection, response, options) { 
     //Will log JSON objects of all User objects 
     console.log(collection.toJSON()); 
     //You can get a Model using 'id' 
     var user = collection.get("hqesig1ea1br2k6horay"); 
     // Will log User Model for id "hqesig1ea1br2k6horay" 
     console.log(user); 
     //You can then fetch Model attributes this way 
     console.log("ID: ", user.get('id')); 
     console.log("First name: ", user.get('firstname')); 
     console.log("Lastname : ", user.get('lastname')); 
    } 
}); 

A fiddle供您參考。