【发布时间】:2014-08-05 16:01:56
【问题描述】:
我正在尝试编写我的第一个 jQuery 插件,但遇到了一个问题;
这是我正在使用的(简化的)代码(插件结构基于this boilerplate template):
;(function ( $, window, document, undefined ) {
var pluginName = "myplugin";
var settingsDefaults = {
example: "value"
};
function Plugin(element, settingsCustom) {
this.element = $(element);
this.settings = $.extend({}, settingsDefaults, settingsCustom);
this._defaults = settingsDefaults;
this._name = pluginName;
this.init();
}
$.extend(Plugin.prototype, {
init: function() {
$.getJSON('/ajax/mydata.json', this.theCallback);
},
theCallback: function(data) {
// do something with data
// call next task
theNextMethod();
},
theNextMethod: function() {
alert('Next Method Called');
}
});
$.fn[pluginName] = function (options) {
this.each(function() {
if(!$.data(this, "plugin_" + pluginName)) {
$.data(this, "plugin_" + pluginName, new Plugin(this, options));
}
});
return this;
};
})(jQuery, window, document);
当在元素上调用插件时调用init 方法,并调用获取一些JSON 的AJAX 请求,在插件中注册另一个方法theCallback。这被称为罚款。在该方法中,我尝试在插件中调用另一个方法(方便地称为theNextMethod),但是它失败了,我在控制台中收到以下错误:
TypeError: 'undefined' 不是函数(评估 'theNextMethod()')
我知道这与使用this 的范围有关,但不确定如何解决。非常感谢任何帮助。
【问题讨论】:
标签: javascript jquery ajax jquery-plugins callback