Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create jquery extension. problems with scope

I create a simple jQuery extension(it's my first).

(function($){
  var MyClass = function(opt){
     //..
  };
  //one of the methods of my extension
  $.fn.myExtension = function(opt){
    this._ext = new MyClass(opt);
    return this;
  };
  $.fn.myExtensionOtherMethod = function(){
    if(this._ext){
      //do something ..
    }
    return this;
  };
}(jQuery));

//using ..
$(document).ready(function(){
  $('#selector').myExtension({
    //options ..
  });
  $('#selector').myExtensionOtherMethod();
});

when i invoke method $('#selector').myExtensionOtherMethod();, this does not contains this._ext variable. I know that this is other scope, but i know that there is some way to access that variable in both methods.how can i do it?

like image 639
Oleh Kurpiak Avatar asked Oct 30 '22 11:10

Oleh Kurpiak


1 Answers

This isn't really a scope issue. This is because the jQuery prototype $.fn gives you a jquery object as this. Even though you are selecting the same element each time its a new jQuery object set as the context so that property is gone. You can put that property on the DOM element and achieve the outcome you want.

(function($) {
    var MyClass = function(opt) {};
    //one of the methods of my extension
    $.fn.myExtension = function(opt) {
        this[0]._ext = new MyClass(opt);
        return this;
    };
    $.fn.myExtensionOtherMethod = function() {
        if (this[0]._ext) {
            //do something ..
        }
        return this;
    };
}(jQuery));

//using ..
$(document).ready(function() {
    $('#selector').myExtension({
        //options ..
    });
    $('#selector').myExtensionOtherMethod();
});

This is just a quick example above. If your selector finds more than one element you should loop though them. But I only grabbed the first index since you were selecting by ID.

Fiddle: https://jsfiddle.net/AtheistP3ace/gd1ehk0d/

As mentioned above by @charlietfl, I agree with that comment. Happy to explain why what you did didn't work but there may be better ways to achieve what you are looking for.

like image 70
AtheistP3ace Avatar answered Nov 11 '22 02:11

AtheistP3ace