【问题标题】:jQuery AJAX callback method unable to access another plugin methodjQuery AJAX 回调方法无法访问另一个插件方法
【发布时间】: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


    【解决方案1】:

    您必须使用正确的命名空间调用方法

    $.extend(Plugin.prototype, {
    
            init: function() {
                $.getJSON('/ajax/mydata.json', this.theCallback.bind(this));
            },
            theCallback: function(data) {
                this.theNextMethod();
            },
    
            theNextMethod: function() {
                alert('Next Method Called');
            }
    
    });
    

    注意它如何将this 的值绑定到回调函数,将其设置为对象,而不是默认情况下$.getJSON 回调中的this 的XHR 对象。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-03
      • 1970-01-01
      • 2013-07-11
      • 1970-01-01
      相关资源
      最近更新 更多