gbuckingham89
gbuckingham89

Reputation: 385

jQuery AJAX callback method unable to access another plugin method

I'm dabbling at writing my first jQuery plugin and have encountered an issue;

Here is the (simplified) code I'm using (the plugin structure is based on 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);

The init method gets called when the plugin is called on the element, and an AJAX request to get some JSON is called, registering another method in the plugin as a callback, theCallback. This gets called fine. Within that method, I then try to call another method in the plugin (handily called theNextMethod), however it fails and I get the following error in the console:

TypeError: 'undefined' is not a function (evaluating 'theNextMethod()')

I understand this has something to do with the scope of using this, but am unsure how to solve it. Any help is much appreciated.

Upvotes: 0

Views: 202

Answers (1)

adeneo
adeneo

Reputation: 318222

You'll have to call the method with the proper namespace

$.extend(Plugin.prototype, {

        init: function() {
            $.getJSON('/ajax/mydata.json', this.theCallback.bind(this));
        },
        theCallback: function(data) {
            this.theNextMethod();
        },

        theNextMethod: function() {
            alert('Next Method Called');
        }

});

Note how it binds the value of this to the callback function, setting it to the object, and not the XHR object which is this inside the callback for $.getJSON by default.

Upvotes: 2

Related Questions