javascript - jQueryPlugin: return this vs return this.each() -


yes, there many topics that, still didn't it:

i prepared 2 jsfiddle:

return this

return this.each()

what's difference? there many answers, examples show same output. some of these answers might wrong!?


what "return this.each()" in jquery?

"it allows 1 call plugin or event on bunch of elements , apply same function or event of them" --> work's "return this well!"

"it allows chain multiple functions" --> same here

"allows things like: $("myselector").foo().show();" --> still can well, when return 'this'


i created jsfiddle shows - in opinion - doesn't matter if you're wrapping code return this.each();:

http://jsfiddle.net/7s3mw/1/

the chrome console show's same output!

so what's difference?

two things:

  1. your examples flawed in same thing each element.
  2. the real issue isn't return this versus return this.each, issue this versus this.each.

for (1), consider difference between plugin:

(function($) {     $.fn.mangle = function(options) {         this.append(' - ' + this.data('x'));         return this;     }; })(jquery); 

demo: http://jsfiddle.net/ambiguous/eyheu/

and plugin:

(function($) {     $.fn.mangle = function(options) {         return this.each(function() {             $(this).append(' - ' + $(this).data('x'));         });     }; })(jquery); 

demo: http://jsfiddle.net/ambiguous/5dmmh/

so see, need use this.each if need treat individual elements in this set differently. have similar effects if plugin had attach element-specific data each element: if didn't use each you'd end attaching exact same piece of data of elements inside this , leave confused why information bleeding on place.

for (2), doesn't matter if return this or return this.each(... since x.each(...) returns x anyway.


Comments

Popular posts from this blog

jasper reports - Fixed header in Excel using JasperReports -

media player - Android: mediaplayer went away with unhandled events -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -