javascript - jQueryPlugin: return this vs return this.each() -
yes, there many topics that, still didn't it:
i prepared 2 jsfiddle:
what's difference? there many answers, examples show same output. some of these answers might wrong!?
"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();
:
the chrome console show's same output!
so what's difference?
two things:
- your examples flawed in same thing each element.
- the real issue isn't
return this
versusreturn this.each
, issuethis
versusthis.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
Post a Comment