Backbone.js 获取实际上并未设置属性 [英] Backbone.js fetch not actually setting attributes

查看:16
本文介绍了Backbone.js 获取实际上并未设置属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基本的主干模型,它的 urlRoot 属性被设置,服务器端的相应目标返回一个正确的 JSON 输出(JSON 字符串和 application/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).

我这样调用 fetch:

I call a fetch like this:

var athlete = new Athlete({ id: 1 });
athlete.fetch();

此时如果我添加一个

console.log(athlete);

我可以看到模型,并在 firebug 中检查它我可以打开属性对象并查看从服务器返回的所有值.

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'));

I get undefined(名称出现在我上面提到的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>);

然后一切正常,.get() 方法返回我要求的任何内容,athlete.attributes 显示所有值.

then everything works fine, the .get() method returns whatever I ask, and athlete.attributes shows all the values.

我做错了什么?

推荐答案

fetch 是异步的,这意味着如果您立即调用 console.log(athlete.get('name')) 在获取之后.

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'));
    }
});

或者利用fetch返回的promise:

or take advantage of the promise returned by fetch:

athlete.fetch().then(function () {
    console.log(athlete.get('name'));
});

这篇关于Backbone.js 获取实际上并未设置属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆