2014-03-29 78 views
0

模型中嘗試了以下內容:Backbone.js的 - 列出包含在集合

var collectionList = users.fetch(); 
alert(collectionList); 

返回null儘管它有成爲模特。

更新 - 這個工作對我來說:

users.fetch({ 
    success: function() { 
     console.log(users.toJSON()); 
    }, 
    error: function() { 
     // something is wrong.. 
    } 
}); 
+0

的'success'功能將被傳遞的收集,所述響應,以及請求的選項。利用顯式傳遞給該函數的集合可能有助於使事情變得更簡潔。 – max

回答

0
users.fetch().then(function() { 
    console.log(users.toJSON()); 
}); 

http://backbonejs.org/#Collection-fetch

+0

試過這個代碼,沒有工作,編譯器抱怨說當我添加了then的時候函數未定義 - 如果我刪除它將返回null。更新我的答案,使用可行的代碼 - 只有包含成功或錯誤時纔有效。 – bobo2000

1
users.fetch({ 
    success: function(response) { 
     _.each(response.models, function(model) { 
      //Do something with the model here 
     }); 
    } 
}); 
+0

謝謝,是_each在js的foreach嗎? – bobo2000

+0

你可以這麼說。這是'underscore.js'。它也由'backbone.js'在內部使用。 –

0

取是異步方法,所以是在被稱爲空的,您可以指定成功和錯誤,你以後應該然後能夠列出你的模型。

users.fetch({ 
    success: function() { 
     console.log(users.toJSON()); 
    }, 
    error: function() { 
     // something is wrong.. 
    } 
}); 
0

這一個也可以

var that = this; 
users.fetch({ 
    success: function(collection, response) { 
     console.log(that.collection.toJSON()); 
    }, 
    error: function() { 
     // something is wrong.. 
    } 
});