How to use 'this' in jQuery plugin callback?

I am currently creating a jQuery plugin.

I am having a problem with a callback.

Plugin code

$.fn.bondye = function (options) { var settings = $.extend({ callback: function () {} }, options); return this.each(function () { $(this).addClass('test'); settings.callback(); }); }; 

How do I want to execute code

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

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

But I can't do anything with the div in the callback.

I used http://learn.jquery.com/plugins/advanced-plugin-concepts/ to study jQuery plugin development, but I can not find anything about callbacks.

+4
source share
3 answers

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

 settings.callback.call(this); 
+6
source

Option 1:

Pass this back when calling 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: (desirable)

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

+2
source

Source: https://habr.com/ru/post/1489257/


All Articles