开发者

Call is undefined

开发者 https://www.devze.com 2023-02-28 13:50 出处:网络
I\'m trying to set up my plugin to accept a callback function inside as a option argument: (function($) {

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 h开发者_如何学Goere)

        });
    };

    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...


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.


settings is not in scope inside of complete().


the variable settings is out of scope in the complete function. Place the complete function in the function where you have defined settings.

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

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

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

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

    });
};
0

精彩评论

暂无评论...
验证码 换一张
取 消