Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use 'this' in jQuery plugin callback?

At the moment I am creating a jQuery plugin.

I am facing a problem when using a callback.

Plugin code

$.fn.bondye = function (options) {
    var settings = $.extend({
        callback: function () {}
    }, options);

    return this.each(function () {
        $(this).addClass('test');
        settings.callback();
    });
};

How I want to execute the code

$(".myDiv").bondye({
    callback: function () {
        $(this).removeClass("test");
    }
});

jsFiddle example: http://jsfiddle.net/HEJtm/1/

But I aint able to do anything with the div within the callback.

I used http://learn.jquery.com/plugins/advanced-plugin-concepts/ to learn developing jQuery plugins, but I cannot find anything about callbacks.

like image 825
Ron van der Heijden Avatar asked Dec 12 '22 13:12

Ron van der Heijden


1 Answers

You need to set the context for your callback. You can use call:

settings.callback.call(this);
like image 147
Mathletics Avatar answered Dec 27 '22 23:12

Mathletics