Get Ember-Data REST response value

非 Y 不嫁゛ 提交于 2020-01-05 07:47:13

问题


Ember: 1.0.0-rc.6

Ember-Data: e999edb (2013-07-06 06:03:59 -0700)

I make a REST call (POST) to login a user. Server response is ok. I need the ID from the server, but i only got the ID with "setTimeout".

I think this is not the right way.

What is my mistake?

Within Controller i call:

var login = App.Login.createRecord(this.getProperties("email", "password"));

login.on("didCreate", function(record) {
  console.log(record.get("id"));     // ID is null
  console.log(record.get("email"));
});

setTimeout(function() {
  console.log(login.get("id"));     // ID is available
  console.log(login.get("email"));
}, 500);

DS.defaultStore.commit();

回答1:


You're right -- there's a bug in ember-data where the materializeData event, which basically sets the id and unwraps the server response doesn't happen until AFTER the didCreate callback. So what's happening is that in your login.on("didCreate" ....) callback, the record still hasn't materialized yet.

This seems to still be an issue -- see this thread for more information: https://github.com/emberjs/data/issues/405#issuecomment-17107045

Workaround

Your work around is fine, but an easier (cleaner?) one is to wrap your callback actions in a Ember.run.next:

login.on("didCreate", function(record) {
  Ember.run.next(function() {
    console.log(record.get("id"));     // ID should be set
    console.log(record.get("email"));
  }
});

This way, at least you don't need to deal with the timeout.

I believe this works by delaying the actions until the next run loop, and by then the materialization should have already happened. More on the Ember run loop

Source: https://github.com/emberjs/data/issues/405#issuecomment-18726035



来源:https://stackoverflow.com/questions/17790671/get-ember-data-rest-response-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!