主干.js获取实际上没有设置属性

Backbone.js fetch not actually setting attributes

本文关键字:设置 属性 实际上 js 获取 主干      更新时间:2023-09-26

我有一个基本的骨干模型,设置了它的urlRoot属性,服务器端的相应目标返回正确的JSON输出(JSON字符串和application/json标头(。

我像这样调用获取:

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

此时,如果我添加一个

console.log(athlete);

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

但是如果我这样做:

console.log(athlete.get('name'));

我得到undefined(名称出现在我上面提到的 DOM 检查中的属性下(

还做一个:

console.log(athlete.attributes);

返回一个仅包含{id: 1}的对象,这是我在创建模型时传递的参数。

如果我像这样创建模型:

var athlete = new Athlete(<JSON string copypasted from the server response>);

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

我做错了什么?

fetch

异步的,这意味着如果您在获取后立即调用console.log(athlete.get('name')),数据将不可用。

使用事件在数据可用时收到通知,例如

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返回的承诺:

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

在这个例子中使用事件时的快速评论一样。在我的情况下,它不适用于change,因为此事件会在每次更改时触发。所以sync诀窍。

var athlete = new Athlete({id: 1});
athlete.on("sync", function (model) {
   console.log(model.get('name'));
});
athlete.fetch();