0

I have a image dimensions calculation function which returns scaled image dimension values when it's executed. (note: the list of images and their dimensions are accessed from the arrays.)

function setDesiredDimensions() {
                var width = Math.min(imagesOrigWidths[currindex], desiredWidthLimit);
                var height = Math.ceil((width / imagesOrigWidths[currindex]) * imagesOrigHeights[currindex]);

                some more calculation code here...

                return {width:width,height:height};
            }     

var size = setDesiredDimensions(imagesOrigWidths[currindex], imagesOrigHeights[currindex]);

Then I have some buttons in HTML:

<a id="button1"></a>
<a id="button2"></a>
<a id="button3"></a>

And various onclick events on these buttons, such as:

$('#button1').click( function() {
     currindex = (currindex+1) % max;

     **I need to evaluate setDesiredDimensions function here **

     $("#imageswap").attr({src: imgSrcBase(imagesGuids[currindex]), width: size.width, height: size.height})
});

The buttons adjust the current image index in the array which I need to apply the dimension calculation on. BUT: I don't want to have the same setDesiredDimensions function copied and pasted in all button click functions, but rather just access/evaluate it as a shortcut for a cleaner code.

I heard eval(); is dangerous and slow. Any ideas?

DominiqueBal
  • 787
  • 1
  • 7
  • 18

1 Answers1

2

If you have define setDesiredDimensions in a scope accessible by all event handlers, you can just call the function. That's what functions are for.

I think your problem is that the function is working with global variables instead of arguments passed to it. In you example, you are passing imagesOrigWidths[currindex] as argument but also access imagesOrigWidths[currindex] inside the function, which does not make sense.

Redefine it so that you can simply pass the arguments it needs, something like

function setDesiredDimensions(orig_width, orig_height, limit) {
    var width = Math.min(orig_width, limit);
    var height = Math.ceil((width / orig_height) * orig_height);

    // some more calculation code here...

    return {width:width,height:height};
}    
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143