在下面的代码中,我调用了loadAuthorsList函数,然后该函数将其信息传递给loadTemplate函数。但是firebug告诉我'this.loadTemplate‘不是一个函数。为什么以及如何修复它?
var LI = {
sFI: x,
loadAuthorsList: function () {
myApp.showPleaseWait();
//for later
$('#records_table').find('tr:gt(0)').remove();
jQuery.ajax({
url: this.sFI.getServiceRoot('A'),
type: 'POST',
dataType: 'json',
data: {},
beforeSend: this.sFI.setModuleHeaders,
success: function (data) {
this.loadTemplate('AuthorTemplate', '#author_records', data)
},
complete: function () {
}
});
},
loadTemplate: function (templateName, selectorName, inputData) {
var jsPath = this.serviceFrameInstructors.getServiceRoot('LearnoogleInstructors');
jQuery.ajax({
url: jsPath.slice(0, -4) + 'js/templates/' + templateName + '.html',// + intArea,
cache: false,
success: function (value) {
var personTemplate = $.templates(value);
var html = personTemplate.render(inputData);
$(selectorName).html(html);
}
});
}
};发布于 2015-06-11 23:48:23
因为在成功回调时,this指向另一个对象(XHR)。您可以使用Function.prototype.bind显式绑定上下文,例如:
success: function (data) {
this.loadTemplate('AuthorTemplate', '#author_records', data)
}.bind(this),或者更简单,您可以将对正确上下文的引用存储在变量中:
var self = this;
jQuery.ajax({
url: this.sFI.getServiceRoot('A'),
type: 'POST',
dataType: 'json',
data: {},
beforeSend: this.sFI.setModuleHeaders,
success: function (data) {
self.loadTemplate('AuthorTemplate', '#author_records', data)
},
complete: function () {
}
});或者更多选项:使用可以使用jQuery context设置来为AJAX回调提供上下文:
context: this,
success: function (data) {
this.loadTemplate('AuthorTemplate', '#author_records', data)
},https://stackoverflow.com/questions/30785520
复制相似问题