我有一个场景,模型的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'
});
因此,当提取问题时:
var issue = new Issue({id: 1});
issue.fetch().then(function(){
//do stuff
});
它将具有包含markdown语法文本的body属性,而我需要将其传递给另一个API并获取将传递给view的响应.
从上面可以看出,我尝试重写parse但它的返回类型必须是一个对象,fetch将是异步的,所以我能做些什么来使这个工作?
注意:我知道聚合服务器中的数据然后接收它将是最好的主意,但这不可能是atm.
解决方法
您可以覆盖问题模型中的
sync method来链接您的请求.
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',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的回调,当您对数据满意时,可以使用它来设置模型的属性.
和一个演示http://jsfiddle.net/puwueqe3/5/