4

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.

4

3 回答 3

6

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

settings.callback.call(this);
于 2013-07-02T10:56:00.283 回答
5

Invoke it as

settings.callback.call(this);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

于 2013-07-02T10:56:06.287 回答
2

Option 1:

Pass this back when you invoke callback():

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

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

            // Pass "this" back here:
            settings.callback(this);
        });
    };

})(jQuery);

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

Here's a working fiddle.

Option 2: (preferred)

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

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

})(jQuery);

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

Here's a working fiddle.

于 2013-07-02T10:57:07.023 回答