Backbone.js的取指没有实际设置属性 [英] Backbone.js fetch not actually setting attributes
问题描述
我有一个基本的骨架模型,其 urlRoot
属性设置,并在服务器端相应的目标会返回一个正确的JSON输出(包括JSON字符串和应用程序/ JSON
头)。
I have a basic backbone model, its urlRoot
attribute is set and the corresponding target on the server side returns a correct JSON output (both JSON string and application/json
header).
我所说的取像这样:
var athlete = new Athlete({ id: 1 });
athlete.fetch();
在这一点上,如果我添加
at this point if I add a
console.log(athlete);
我可以看到模型,并在萤火检查它,我可以打开属性对象,看到从服务器返回的所有值。
I can see the model, and inspecting it in firebug I can open the attributes object and see all the values returned from the server.
但是,如果我做了:
console.log(athlete.get('name'));
我得到未定义
(名称出现下我上面提到的DOM检查属性)
I get undefined
(the name appears under the attributes in the DOM inspection I mentioned above)
也做了:
console.log(athlete.attributes);
返回包含对象只 {ID:1}
这是在创建模型我传递的参数
returns an object containing only {id: 1}
which is the argument I passed while creating the model.
如果我创建这样的模型:
If I create the model like this:
var athlete = new Athlete(<JSON string copypasted from the server response>);
然后一切工作正常,在获得()
方法返回什么就给什么,而 athlete.attributes
节目所有的值。
then everything works fine, the .get()
method returns whatever I ask, and athlete.attributes
shows all the values.
我在做什么错了?
推荐答案
取
是异步的,这意味着数据将不可用,如果你立刻打电话的console.log(athlete.get('名'))
后获取。
fetch
is asynchronous, which means that the data won't be available if you immediatly call console.log(athlete.get('name'))
after the fetch.
当数据是可用的,被通知使用事件例如:
Use events to be notified when the data is available, for example
var athlete = new Athlete({id: 1});
athlete.on("change", function (model) {
console.log(model.get('name'));
});
athlete.fetch();
或回调添加到您获取
var athlete = new Athlete({ id: 1 });
athlete.fetch({
success: function (model) {
console.log(model.get('name'));
}
});
或采取由返回的承诺获取的优势
:
athlete.fetch().then(function () {
console.log(athlete.get('name'));
});
这篇关于Backbone.js的取指没有实际设置属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!