2012-01-18 127 views
0

我在這裏做的事情完全錯誤嗎?我從jsonp響應中填充骨幹模型。當我在firebug中查看第一個控制檯語句時,「當前」對象在屬性下具有「圖標」。但是,在打印console.log(current.has("icon"))時,它返回false,因此current.get(「icon」)將返回undefined。Backbone.js模型

var Current = Backbone.Model.extend({ 
    url: "A_valid_url", 
    sync: function(method, model, options) { 
     options.timeout = 10000; 
     options.dataType = "jsonp"; 

     return Backbone.sync(method, model, options); 
    }, 
    parse: function(response, xhr) { 
     return response.current_observation; 
     } 
}); 

var current = new Current({test: "blah"}); 
    current.fetch(); 
    console.log(current);//under attributes there is a "icon" 
    console.log(current.has("icon")); //false 
    console.log(current.get("icon")); //undefined 
    console.log(current.has("test")); //true 

回答

2

fetch()是異步的。請嘗試以下操作:

var current = new Current({test: "blah"}); 
current.fetch({ 
    success: function(){ 
     console.log(current.get("icon")); 
    } 
); 
+0

grr我知道這是愚蠢和簡單的事情。謝謝! – flynfish 2012-01-18 02:04:46

+0

太棒了 - 很高興它有幫助 – timDunham 2012-01-18 02:08:37

0
current.fetch(); 
console.log(current);//under attributes there is a "icon" 
console.log(current.has("icon")); //false 
console.log(current.get("icon")); //undefined 
console.log(current.has("test")); //true 

是,真正的代碼?如果是這樣,所有這些日誌記錄將在之前發生數據的異步加載已完成。您需要在回調中執行此操作(或綁定到模型上的「更改」事件)。

console.log(current);//under attributes there is a "icon" 

該數據仍然在控制檯日誌中顯示出來是當你登錄的對象(而不是字符串)日誌的「feature」:它只能傳遞一個參考,實際印刷後會發生(當數據可能已經被加載)。