英文原文:http://emberjs.com/guides/models/persisting-records/

Ember Data中的记录都基于实例来进行持久化。调用DS.Model实例的save()会触发一个网络请求,来进行记录的持久化。

下面是几个示例:

  1. var post = store.createRecord('post', {
  2. title: 'Rails is Omakase',
  3. body: 'Lorem ipsum'
  4. });
  5. post.save(); // => POST to '/posts'
  1. var post = store.find('post', 1);
  2. post.get('title') // => "Rails is Omakase"
  3. post.set('title', 'A new post');
  4. post.save(); // => PUT to '/posts/1'

承诺

save()会返回一个承诺,这使得可以非常容易的来处理保存成功和失败的场景。下面是一个通用的模式:

  1. var post = store.createRecord('post', {
  2. title: 'Rails is Omakase',
  3. body: 'Lorem ipsum'
  4. });
  5. var self = this;
  6. function transitionToPost(post) {
  7. self.transitionToRoute('posts.show', post);
  8. }
  9. function failure(reason) {
  10. // handle the error
  11. }
  12. post.save().then(transitionToPost).catch(failure);
  13. // => POST to '/posts'
  14. // => transitioning to posts.show route

对于失败的网络请求,承诺也可以方便的来处理:

  1. var post = store.createRecord('post', {
  2. title: 'Rails is Omakase',
  3. body: 'Lorem ipsum'
  4. });
  5. var onSuccess = function(post) {
  6. this.transitionToRoute('posts.show', post);
  7. };
  8. var onFail = function(post) {
  9. // deal with the failure here
  10. };
  11. post.save().then(onSuccess, onFail);
  12. // => POST to '/posts'
  13. // => transitioning to posts.show route

更多关于承诺的内容请参看这里,下面是一个示例展示了如何在重试失败的持久化操作:

  1. function retry(callback, nTimes) {
  2. // if the promise fails
  3. return callback().fail(function(reason) {
  4. // if we haven't hit the retry limit
  5. if (nTimes-- > 0) {
  6. // retry again with the result of calling the retry callback
  7. // and the new retry limit
  8. return retry(callback, nTimes);
  9. }
  10. // otherwise, if we hit the retry limit, rethrow the error
  11. throw reason;
  12. });
  13. }
  14. // try to save the post up to 5 times
  15. retry(function() {
  16. return post.save();
  17. }, 5);