JQuery cannot access $ (this) in callback function

I am creating a plugin and cannot access $ (this). A simple overview of my plugin is

(function($){
    $.fn.myPlugin= function(options, callback) {
        return this.each(function(){
                $(this).click(function(){
                      // some plugin works ..

                      callback();
                });
        });
    };

})(jQuery);

Then I attached my plugin to an element of type

$('p').myPlugin({
      // Some options
}, function(){
      alert('first test');
      alert($(this).text());
});

Here, when the element p is clicked, I get the first warning, but I did not get the second warning.

The callback function is called, but cannot access this. Is there a problem with the definition or with the code? any alternative suggestion would also be helpful

+3
source share
3 answers

Instead, callback();use .apply()to give it the correct context (otherwise it window), for example:

callback.apply(this);

/ .


, , callback, , options, :

(function($){
  $.fn.myPlugin= function(options, callback) {
    return this.each(function(){
      $(this).click(function(){
        callback.apply(this, [options]);
     });
   });
 };
})(jQuery);

:

$('p').myPlugin({
    thing: "thing1"
}, function(opts){
    alert(opts.thing); //thing1
});​

, , , callback() :)

+4
+1

, ?

...

    $('.suggest').autocomplete({
    source: function(request, response) {
        typ = $(this).getAttr("class").split(" ")[2]
        ....

... undefined. document.activeElement, Nick Craver.

0
source

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


All Articles