入门指南 获取Ember 概念 对象模型 应用 模板 路由 组件 控制器 模型 视图 枚举 测式 配置Ember.js COOKBOOK 理解Ember.js

发布于 2015-08-18 16:38:49 | 254 次阅读 | 评论: 0 | 来源: 网络整理

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

下面是几个示例:

 
1
2
3
4
5
6
var post = store.createRecord('post', {
  title: 'Rails is Omakase',
  body: 'Lorem ipsum'
});

post.save(); // => POST to '/posts'
 
 
1
2
3
4
5
6
7
var post = store.find('post', 1);

post.get('title') // => "Rails is Omakase"

post.set('title', 'A new post');

post.save(); // => PUT to '/posts/1'
 

承诺

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

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var post = store.createRecord('post', {
  title: 'Rails is Omakase',
  body: 'Lorem ipsum'
});

var self = this;

function transitionToPost(post) {
  self.transitionToRoute('posts.show', post);
}

function failure(reason) {
  // handle the error
}

post.save().then(transitionToPost).catch(failure);

// => POST to '/posts'
// => transitioning to posts.show route
 

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

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var post = store.createRecord('post', {
  title: 'Rails is Omakase',
  body: 'Lorem ipsum'
});

var onSuccess = function(post) {
  this.transitionToRoute('posts.show', post);
};

var onFail = function(post) {
  // deal with the failure here
};

post.save().then(onSuccess, onFail);

// => POST to '/posts'
// => transitioning to posts.show route
 

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

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

    // otherwise, if we hit the retry limit, rethrow the error
    throw reason;
  });
}

// try to save the post up to 5 times
retry(function() {
  return post.save();
}, 5);
 
最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务