2012-02-24 110 views
16

我想一些數據加載到骨幹網收集從本地JSON文件,使用這種非常基本的代碼:從JSON文件將數據加載到Backbone集合中?

window.Student = Backbone.Model.extend({ 
    }); 
    window.Students = Backbone.Collection.extend({ 
    model: Student, 
    }); 
    window.AllStudents = new Students(); 
    AllStudents.fetch({ url: "/init.json"}); 
    console.log('AllStudents', AllStudents); 

在控制檯中陳述,AllStudents是空的。但是init.json肯定會被加載。它看起來像這樣:

[ 
    { text: "Amy", grade: 5 }, 
    { text: "Angeline", grade: 26 }, 
    { text: "Anna", grade: 55 }  
] 

我在做什麼錯?

更新:我也嘗試添加一個reset聽者.fetch()撥打以上,但是這不點火之一:

AllStudents.bind("reset", function() { 
    alert('hello world'); 
}); 
AllStudents.fetch({ url: "/init.json"}); 

中不會顯示警報。

更新2:嘗試這個腳本(在這裏充分轉載):

$(function(){ 
    window.Student = Backbone.Model.extend({ 
    }); 
    window.Students = Backbone.Collection.extend({ 
    model: Student, 
    }); 
    window.AllStudents = new Students(); 
    AllStudents.url = "/init.json"; 
    AllStudents.bind('reset', function() { 
     console.log('hello world'); 
    }); 
    AllStudents.fetch(); 
    AllStudents.fetch({ url: "/init.json", success: function() { 
     console.log(AllStudents); 
    }}); 
    AllStudents.fetch({ url: "/init.json" }).complete(function() { 
     console.log(AllStudents); 
    }); 
}); 

只有一個控制檯聲明甚至出現在第三fetch()通話,這是一個空的對象。

我現在絕對很困惑。我究竟做錯了什麼?

JSON文件被作爲應用程序/ json提供,所以它與此無關。

+1

這是一個很好的問題。你應該使用http://jsonlint.com/來驗證你的JSON – 2014-07-03 20:59:51

回答

0

我認爲你需要添加{add:true}獲取的選項,

如果您分配了取到一個變量,你會得到的結果爲好, 但隨後它不是集合裏面你想

+0

我不認爲這是正確的 - '{add:true}'添加,而不是替換內容,但我想替換內容。 – Richard 2012-02-24 16:43:19

10

在javascript中的I/O操作幾乎總是異步的,所以它也與Backbone一起使用。這意味着僅僅因爲AllStudents.fetch已經返回,它還沒有獲取數據。所以當你點擊你的console.log聲明時,資源還沒有被提取。你應該通過回調來fetch

AllStudents.fetch({ url: "/init.json", success: function() { 
    console.log(AllStudents); 
}}); 

或可選,使用jQuery的新承諾的功能(fetch會返回一個承諾):

AllStudents.fetch({ url: "/init.json" }).complete(function() { 
    console.log(AllStudents); 
}); 
+0

嗯 - 那個控制檯語句永遠不會出現 - 好像成功永遠不會被觸發。 'init.json'文件正在被加載,但... – Richard 2012-02-24 16:40:54

1

fetch()方法返回一個 '成功' 的通知,已經說過,但這只是表示服務器請求已成功。 fetch()帶回了一些JSON,但它仍然需要將其填充到集合中。

集合在內容更新時觸發'重置'事件。這是當收集準備使用...

AllStudents.bind('reset', function() { alert('AllStudents bind event fired.'); }); 

它看起來像你有你的第一次更新。我做的唯一不同的是把fetch()放在事件綁定的前面。

17

JSON文件中的屬性名稱和非數字屬性值必須用雙引號(「」)。單引號或不引號會產生錯誤,並且不會創建可用於創建模型和填充集合的響應對象。

所以。如果您將json文件內容更改爲:

[ 
    { "text": "Amy", grade: 5 }, 
    { "text": "Angeline", grade: 26 }, 
    { "text": "Anna", grade: 55 }  
] 

您應該看到非空集合對象。

你可以改變你的代碼,看看成功和失敗如下:

AllStudents.fetch({ 
    url: "/init.json", 
    success: function() { 
      console.log("JSON file load was successful", AllStudents); 
     }, 
    error: function(){ 
     console.log('There was some error in loading and processing the JSON file'); 
    } 
    }); 

有關詳細信息,因爲這可能是在尋找的方式AJAX創建響應對象是個好主意。

+1

你是對的。這是正確的答案。這是正確的答案 – 2014-07-03 20:58:21