Search code examples
javascriptjquerycallbackcalljquery-callback

Call is undefined


I'm trying to set up my plugin to accept a callback function inside as a option argument:

(function($) {

    $.fn.MyjQueryPlugin = function(options) {
        var defaults = {
            onEnd: function(e) {}
        };

        var settings = $.extend({}, defaults, options);

        return this.each(function() {
            // do stuff (complete() gets called here)

        });
    };

    function complete(e){
        settings.onEnd.call(this); // <- the error?
    }

})(jQuery);

But I get a error that call() is undefined. What's wrong with my code?

ok, I changed this with:

(function($) {

    $.fn.MyjQueryPlugin = function(options) {
        var defaults = {
            onEnd: function(e) {}
        };

        var settings = $.extend({}, defaults, options);

        var complete = function(e){
          settings.onEnd.call(this); // <- the error?
        }


        return this.each(function() {
            // do stuff (complete() gets called here)

        });
    };   

})(jQuery);

and the error is still there...


Solution

  • You're trying to reference settings outside of the function in which it's defined. You've scoped settings to be a local variable within the function you assign to $.fn.MyjQueryPlugin, but then you're using it from a function that doesn't close over that local variable.

    You could create a new complete function for every call to MyjQueryPlugin that closes over settings:

    (function($) {
    
        $.fn.MyjQueryPlugin = function(options) {
            var defaults = {
                onEnd: function(e) {}
            };
    
            var settings = $.extend({}, defaults, options);
    
            return this.each(function() {
                // do stuff (complete() gets called here)
    
            });
    
            // `complete` now closes over `settings`
            function complete(e){
                settings.onEnd.call(this); // <- the error?
            }
        };
    
    })(jQuery);
    

    ...but of course that involves creating a function. Maybe that's fine, depends on what the plug-in does.

    Alternately, pass settings into complete as an argument.