timothytoe wrote:

: This next one is obviously a work of JavaScript art (as opposed to the
: former, which is a more jQuery solution).

    Actually, it's very jQuery-ish. We can use a similar form to add
custom methods to the jQuery object.



: Does anyone want to explain it?
: 
:  for ( i=0;i<5;i++ ) {
:     (function(num) {
:         $("#port"+num).click(function() { bigchart(num) });
:     })(i);
:  }

    In javascript, you can force a block of code to run by wrapping it in
two sets of parentheses ( ... code ... )(). For example, this function will
not run
until it is called and being anonymous (it has not been assigned to a
variable) there is no way to call it:

function(num) {
   $("#port"+num).click(function() { bigchart(num) });
};

    But, if I wrap it in parenthesis like this, it will run as it is
encountered.

(function(num) {
   $("#port"+num).click(function() { bigchart(num) });
})();

    The problem is that num remains undefined. To define it we can pass
a value in the second parenthesis. This set of five routines will run
for each value 0 through 4.

(function(num) {
   $("#port"+num).click(function() { bigchart(num) });
})(0);

(function(num) {
   $("#port"+num).click(function() { bigchart(num) });
})(1);

(function(num) {
   $("#port"+num).click(function() { bigchart(num) });
})(2);

(function(num) {
   $("#port"+num).click(function() { bigchart(num) });
})(3);

(function(num) {
   $("#port"+num).click(function() { bigchart(num) });
})(4);

    That's an awful lot to type. To bad we aren't programmers, then we
could write a loop to step through the values passed to ... Hey, we are
programmers! Carpenters of the future and all that.

for ( i = 0; i < 5 ;i++ ) {
   (function(num) {
       $("#port"+num).click(function() { bigchart(num) });
   })(i);
}


HTH,

Charles K. Clarkson
-- 
Mobile Homes Specialist
Free Market Advocate
Web Programmer

254 968-8328

http://www.clarksonenergyhomes.com/wordpress/about/

Reply via email to