Backbone.js fetch not actually setting attributes

后端 未结 2 1781
不思量自难忘°
不思量自难忘° 2020-11-29 10:07

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

2条回答
  •  粉色の甜心
    2020-11-29 10:34

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

    or add a callback to your fetch

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

    or take advantage of the promise returned by fetch:

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

提交回复
热议问题