Create a jquery extension. coverage problems

I am creating a simple jQuery extension (this is 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 call the $('#selector').myExtensionOtherMethod(); , this does not contain the variable this._ext . I know this is a different area, but I know that there is some way to access this variable in both methods. How can i do this?

+5
source share
1 answer

This is not a scale problem. This is because the jQuery $.fn provides a jquery object like this . Even though you select the same element every time its new jQuery object is set as a context so that the property is not there. You can put this property in a DOM element and achieve the desired result.

 (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 focus on them. But I just grabbed the first index, since you were picking by ID.

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

As @charlietfl mentioned above, I agree with this comment. I am glad to explain why what you did did not work, but there may be better ways to achieve what you are looking for.

+2
source

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


All Articles