0

I am trying to pass a boolean parameter to a callback from inside a jquery plugin but parameter is always undefined.

The onSwitch callback parameter should alternate between true and false each time the link is clicked. Using a debugger I can see that the value passed to callback call function is properly defined as true or false but inside the callback implementation it turns to undefined.

I have tried looking at several other similar questions like this this and this but cannot seem to get this to work.

This is my plugin definition:

(function ($) {
    $.fn.switcherButton = function (options) {
        // Set the default options
        var settings = $.extend({},$.fn.switcherButton.defaults, options);

        this.click(function () {
            $.fn.switcherButton.switched = !$.fn.switcherButton.switched;
            settings.onSwitch.call($.fn.switcherButton.switched);
        });
        return this;
    };
    // Plugin defaults – added as a property on our plugin function.
    $.fn.switcherButton.defaults = {
        onSwitch: function() {}
    };
    $.fn.switcherButton.switched = false;
}(jQuery));

HTML:

<a id="switchTest" href="#">switch</a>

plugin initialization:

$("#switchTest").switcherButton({
    onSwitch: function(switched){
        if(typeof switched === "undefined")
            alert("callback param = undefined");
        else
            if(switched)
                alert("callback param = true");
            else
                alert("callback param = false");
    }
});

I have created a jsfiddle of the problem here.

1
  • Check this. Commented Aug 19, 2015 at 12:47

1 Answer 1

0

Change settings.onSwitch.call($.fn.switcherButton.switched) to settings.onSwitch($.fn.switcherButton.switched)

Call is used to set this and not the actual argument to the function

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that was an embarrassingly easy fix.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.