[jQuery] Unwanted side effects when jQuery object is empty?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<HTML>
<HEAD>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=us-ascii">
<META NAME="Generator" CONTENT="MS Exchange Server version 6.5.7036.0">
<TITLE>Unwanted side effects when jQuery object is empty? </TITLE>
</HEAD>
<BODY>
<!-- Converted from text/rtf format -->
<BR>
<P><FONT SIZE=2 FACE="Arial">I'm a very green jQuery user, so apologies if I've missed something obvious …</FONT>
</P>
<P><FONT SIZE=2 FACE="Arial">I have a line of code that reads</FONT>
</P>
<P> <FONT SIZE=2 FACE="Arial">$(".rounded").removeClass("rounded").wrap(env("div", "test", {"class":"rounded"}));</FONT>
</P>
<P><FONT SIZE=2 FACE="Arial">env() is a function that (with these parameters) generates the string '<div class="rounded">test</div>'.</FONT>
</P>
<P><FONT SIZE=2 FACE="Arial">The intention is that, for any element with class 'rounded', that class is removed from the element, and the element is wrapped by the given div.</FONT></P>
<P><FONT SIZE=2 FACE="Arial">This works fine when there are one or more elements with class 'rounded'. It also seems to work fine when there are no such elements, but when I (for some another reason) put a diagnostic alert into env(), I found that the function was being called once even though no html was generated.</FONT></P>
<P><FONT SIZE=2 FACE="Arial">I can avoid the problem by rewriting the code as something like</FONT>
</P>
<P> <FONT SIZE=2 FACE="Arial">$(".rounded").removeClass("rounded").each(function(){$(this).wrap(env("div", "test", {"class":"rounded"}))});</FONT>
</P>
<P><FONT SIZE=2 FACE="Arial">That seem a bit of a shame. Or I can avoid it by not having side effects in my functions - usually a good idea, but I was surprised that the function was called at all.</FONT></P>
<P><FONT SIZE=2 FACE="Arial">Any insights?</FONT>
</P>
<P><FONT SIZE=2 FACE="Arial">Alan Williams</FONT>
<BR><FONT SIZE=2 FACE="Arial"> </FONT>
</P>
<BR>
<BR>
</BODY>
</HTML>_______________________________________________
jQuery mailing list
discuss@jquery.com
http://jquery.com/discuss/