gpt4 book ai didi

javascript - Backbone 中的 .get() 问题

转载 作者:行者123 更新时间:2023-12-02 18:56:50 25 4
gpt4 key购买 nike

我已经为这个问题奋斗了一段时间,我想我应该屈服并在这里问,而不是继续用头撞 table 。这是非常基本的东西,我只是从 Backbone 开始。为什么我无法通过 .get() 函数访问 person?

我正在使用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'

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

最佳答案

你有两个问题。

返回单个对象而不是数组。

$.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'

关于javascript - Backbone 中的 .get() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15258192/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com