Is $ (this) required with the standard jQuery plugin template

I followed the standard way to create jQuery plugins. In particular, a bit about not polluting the fn namespace. But I came across some strange things where he breaks his own rule to never use $(this) .

 var methods = { init : function( options ) { return this.each(function(){ var $this = $(this), //HERE data = $this.data('tooltip'), tooltip = $('<div />', { text : $this.attr('title') }); // If the plugin hasn't been initialized yet if ( ! data ) { /* Do more setup stuff here */ $(this).data('tooltip', { target : $this, tooltip : tooltip }); } }); }, 

Is revaluation of this significant in this particular case? If so, why?

+4
source share
2 answers

Yes it is.

Inside the method, this refers to the jQuery object that was used to call the plugin, but you use each to scroll through these elements. In the callback for each , this refers to the DOM element from the jQuery object, so you need to create a new jquery object for each element in order to use jQuery methods on it.

+2
source

In a loop, each this is a DOM element, so yes $(this) is important for using jquery methods on it.

The rule "never use $(this) " refers to what you return. A method that returns $(this) instead of this breaks pointers, such as the prevObject property, which is used by the jquery end method.

0
source

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


All Articles