2013-03-06 82 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" 
     } 
    });