Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
417 views
in Technique[技术] by (71.8m points)

javascript - Backbone.js fetch not actually setting attributes

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).

I call a fetch like this:

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

at this point if I add a

console.log(athlete);

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.

BUT if I do a:

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

I get undefined (the name appears under the attributes in the DOM inspection I mentioned above)

also doing a:

console.log(athlete.attributes);

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

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

What am I doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...