我有一个场景,模型的 fetch()
调用将返回数据,需要从中将属性传递给另一个 API,而该 API 的返回类型将是实际需要的数据。
var Issue = Backbone.Model.extend({
urlRoot: 'https://api.github.com/repos/ibrahim-islam/ibrahim-islam.github.io/issues',
parse: function(response, options){
var markdown = new Markdown({ text : response.body });
markdown.fetch({
contentType: 'application/json',
type: 'POST',
data: JSON.stringify( markdown.toJSON() ),
success: function(data){
response.body = data;
}
});
return response;
}
});
var Markdown = Backbone.Model.extend({
defaults:{
'text': '',
'mode' : 'markdown'
},
url: 'https://api.github.com/markdown'
});
因此,当一个 Issue
将被获取时:
var issue = new Issue({id: 1});
issue.fetch().then(function(){
//do stuff
});
它将有一个 body
属性,其中包含 markdown 语法文本,我需要将其传递给另一个 API 并获取将传递给 View 的响应。
从上面可以看出,我尝试覆盖 parse
但它的返回类型必须是一个对象并且 fetch
将是 async
所以我可以在这里做什么来完成这项工作?
注意:我知道在服务器中聚合数据然后接收它是最好的主意,但这在 atm 上是不可能的。
最佳答案
您可以覆盖 sync method在您的 Issue
模型中链接您的请求。
var Issue = Backbone.Model.extend({
urlRoot: 'https://api.github.com/repos/ibrahim-islam/ibrahim-islam.github.io/issues',
sync: function(method, model, options) {
if (method !== 'read')
return Backbone.sync.apply(this, arguments);
// first request
var xhr = Backbone.ajax({
type: 'GET',
dataType: 'json',
url: _.result(model, 'url')
});
// second request
return xhr.then(function (resp1) {
var markdown = new Markdown({text : resp1.body || 'body'});
var data = markdown.toJSON();
// the callback to fill your model, will call parse
var success = options.success;
return Backbone.ajax({
url: _.result(markdown, 'url'),
dataType: 'html',
contentType: 'application/json',
type: 'POST',
data: data
}).then(function(resp2) {
// sets the data you need from the response
var resp = _.extend({}, resp1, {
body: resp2
});
// fills the model and triggers the sync event
success(resp);
// transformed value returned by the promise
return resp;
});
});
}
});
传递给 Model.sync
的选项散列包含对 model.parse
的回调,当您满意时,您可以使用它来设置模型的属性你的数据。
关于javascript - 主干模型 : Ajax request in parse override,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31674238/