2013-03-06 62 views
0

我一直在爲這個問題苦苦掙扎了一陣子,並且以爲我只會放棄並問問這裏,而不是繼續將我的頭撞向我的桌子。這是非常基本的東西,我只是從骨幹開始。爲什麼我不能通過.get()函數訪問人員?。主題中的get()問題

我使用Mockjax我的Ajax代碼和看起來像這樣:

$.mockjax({ 
    url: '/data', 
    contentType: 'text/json', 
    responseTime: 150, 
    type: 'GET', 
    responseText: '[{ "name": "Chance, Churc", "id_number": "", "w_time": null, "o_time": null }]' 
}); 

和骨幹部分:

var PWItem = Backbone.Model.extend({}); 
var person = new PWItem(); 
person.fetch({ 
    url: '/data', 
    success: function() { 
     console.log(person.attributes[0].name); //this prints the correct attribute 
    } 
}): 

console.log(person); //prints the person object 
console.log(person.get('name')); //prints 'undefined' 

爲骨幹中午任何幫助,將不勝感激。

+0

取是異步的,所以你需要把在執行console.log一個函數,然後調用該函數時,成功處理程序觸發 – Matt 2013-03-06 21:24:53

回答

2

你有兩個問題。

返回單個對象而不是數組。

$.mockjax({ 
    url: '/data', 
    contentType: 'text/json', 
    responseTime: 150, 
    type: 'GET', 
    // you are fetching a single model, so JSON should not be an array 
    responseText: '{ "name": "Chance, Churc", "id_number": "", "w_time": null, "o_time": null }' 
}); 

等到獲取完成後才能訪問屬性。

var PWItem = Backbone.Model.extend({}); 
var person = new PWItem(); 
person.fetch({ 
    url: '/data', 
    success: function() { 
     // this will only work after success 
     console.log(person.get('name')); // should print "Chance, Churc" 
    } 
}): 

person.on('change:name', function(){ 
    console.log(person.get('name')); // should print "Chance, Churc" 
}); 

console.log(person); //prints the person object 
// fetch is not done yet, 'undefined' is expected. 
console.log(person.get('name')); //prints 'undefined' 
+0

不能相信我錯過了射擊的console.log AJAX調用之前完成。很尷尬。我想當你嘗試新的東西時,你會尋找新的答案,而不是你永遠以前做的舊答案。謝謝! – smykes 2013-03-07 12:40:36

0

你試過這樣嗎?

$.mockjax({ 
    url: '/data/1', 
    contentType: 'text/json', 
    responseTime: 150, 
    type: 'GET', 
    responseText: '{ "name": "Chance, Churc", "id_number": "", "w_time": null, "o_time":  null }' 
}); 


var PWItem = Backbone.Model.extend({}); 
var person = new PWItem({url: '/data', id: 1}); 
person.fetch(); 
console.log(person.get('name')); 
0

你寫的模擬ajax是爲了獲取數據的集合。 []。您可以通過點擊url終點/data來獲取收藏集。您可以定義一個集合並使用如下。

var PWItemColl = Backbone.Collection.extend({ 
    model: PWItem 
    url: '/data' 
    }); 

    var persons = new PWItemColl(); 
    persons.fetch ({ 
     success: function() { 
     console.log(persons.at(0).get('name')); // "Chance, Churc" 
     } 
    });