【问题标题】:Backbone.js fetch not actually setting attributesBackbone.js 获取实际上并没有设置属性
【发布时间】:2012-03-06 13:43:28
【问题描述】:

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

我这样调用 fetch:

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 显示所有值。

我做错了什么?

【问题讨论】:

    标签: javascript backbone.js


    【解决方案1】:

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

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

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

    或为您的 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'));
    });
    

    【讨论】:

    • 当然,现在我意识到这是多么明显,感谢您指出:)
    【解决方案2】:

    在本例中使用事件时,作为一个简短的说明。在我的情况下,它不适用于change,因为每次更改都会触发此事件。所以sync 确实 诀窍。

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

    【讨论】:

      猜你喜欢
      • 2020-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-21
      • 2015-02-09
      • 2011-01-01
      • 1970-01-01
      相关资源
      最近更新 更多