Backbone.js fetch not actually setting attributes

后端 未结 2 1764
不思量自难忘°
不思量自难忘° 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:15

    Just as a quick remark when using events in this example. It did not work with change in my case because this events fire on every change. So sync does the trick.

    var athlete = new Athlete({id: 1});
    athlete.on("sync", function (model) {
       console.log(model.get('name'));
    });
    athlete.fetch();
    
    0 讨论(0)
  • 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'));
    });
    
    0 讨论(0)
提交回复
热议问题