我有一个点击处理程序,它通过模板方法获取要注入的 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();
},
}