我有一个点击处理程序,它通过模板方法获取要注入的HTML字符串。现在它不能异步返回回调中的HTML字符串,但我听说如果我使用jQuery defereds我可以实现这一点。但是,在阅读它们之后,我仍然不确定如何构建它。
以下是我的代码的简化版本:
var api_response;
var templates = {
inputSurveyList: function(){
coApi.get_survey_list(function(data){
api_response = data;
});
var buildSurveyList = function() {
var element_list = '';
$.each(api_response, function(index, survey){
element_list += '<option value="' + survey.survey_id + '">' + survey.name + '</option>\n'
});
return element_list
}
var template = '<select class="input-survey-list" name="state">\n' + buildSurveyList() + '</select>';
return template;
}
}
$(foo).click(function(){
$(bar).html(templates.inputSurveyList());
})
这就是API方法的样子:
var Request = function(method, parameters, callback, errback){
var self = this;
this.method = method;
this.parameters = parameters;
this.callback = callback;
this.errback = errback;
this.send = function(){
$.ajax({
dataType: 'json',
type: 'POST',
data: JSON.stringify({method: self.method, params: self.parameters}),
url: '/api',
success: function(data, textStatus, jqXHR){
self.callback(data.response);
},
error: function(jqXHR, textStatus, errorThrown){
if (self.errback) {
self.errback(ajaxRequest);
}
}
});
}
}
var coAPI = {
// Project Calls
get_survey_list: function(callback, errback){
var request = new Request('get_survey_list', {}, callback, errback);
request.send();
},
autocomplete_us_cities: function(term, callback, errback){
var request = new Request('autocomplete_us_cities', {term: term}, callback, errback);
request.send();
},
}
答案 0 :(得分:0)
您的$ .ajax需要自行返回,所以return $.ajax({...})
,然后在get_survey_list: functi...
中需要return request.send()
现在你可以这样使用它:
var templates = {
inputSurveyList: function(callback){
if (!callback) return; // if there's no callback, why generate template?
var api_response = coApi.get_survey_list();
var buildSurveyList = function(data) {
var element_list = '';
$.each(data, function(index, survey){
element_list += '<option value="' + survey.survey_id + '">' + survey.name + '</option>\n'
});
return element_list
}
api_response.done(function(data){
var template = '<select class="input-survey-list" name="state">\n' + buildSurveyList(data) + '</select>';
callback.call(null,template);
});
}
}
$(foo).click(function(){
templates.inputSurveyList(function(template){
$(bar).html(template);
});
});
如果您愿意,可以进一步修改它以使inputSurveyList返回它自己的延迟对象。