Backbone中的.get()问题

时间:2013-03-06 21:13:27

标签: javascript backbone.js

我一直在努力争取这一段时间,我想我会屈服并在这里问,而不是继续把我的脑袋撞到我的桌子上。这是非常基本的东西,我只是从骨干开始。为什么我不能通过.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 }]'
});

和Backbone部分:

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'

对中午的任何帮助都不胜感激。

3 个答案:

答案 0 :(得分: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 }'
});

等到fetch完成后才能访问属性。

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' 

答案 1 :(得分: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'));

答案 2 :(得分:0)

您编写的模拟ajax用于获取数据集合。 []。您可以通过点击网址结束点/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"
      }
    });