Mikioo / sharpkit

Automatically exported from code.google.com/p/sharpkit
0 stars 0 forks source link

Wrong code generation for foreach loop, doesn't respect scope of variables #318

Open GoogleCodeExporter opened 8 years ago

GoogleCodeExporter commented 8 years ago
foreach (PriceRange priceRange in priceRanges)
            {
                ...
                elem.click((e) =>
                    {
                        console.log(priceRange);
                    });
            }

You don't respect foreach variable scope!!!

This is what is see now >>
for (var $i2 = 0, $l2 = priceRanges.length, priceRange = priceRanges[$i2]; $i2 
< $l2; $i2++, priceRange = priceRanges[$i2])
    {
        ...
        elem.click(function (e)
        {
            console.log(priceRange);
        });
    }

This is what is expect >>>
for (var $i2 = 0, $l2 = priceRanges.length, priceRange = priceRanges[$i2]; $i2 
< $l2; $i2++, priceRange = priceRanges[$i2])
    {
        (function(priceRange) {
            ...
            elem.click(function (e)
            {
                console.log(priceRange);
            });
        })(priceRange);
    }

I'm using windows 2012, exporting class with JsMode.prototype, sharpkit 5.2.0

Original issue reported on code.google.com by krunosla...@gmail.com on 29 Sep 2013 at 7:42

GoogleCodeExporter commented 8 years ago
This is a known issue, current workaround requires you to move the loop body 
into method with parameters, this will give you the behavior you want. I 
haven't gotten around to create a generalized automatic solution for it.

Original comment by DanelK...@gmail.com on 10 Oct 2013 at 11:50

GoogleCodeExporter commented 8 years ago
Well, I think this is a pretty huge issue :) I know of a workaround.

Original comment by krunosla...@gmail.com on 13 Oct 2013 at 10:11

GoogleCodeExporter commented 8 years ago
You mean besides extracting the loop body into a new method?

Original comment by DanelK...@gmail.com on 14 Oct 2013 at 4:54

GoogleCodeExporter commented 8 years ago
Well extracting into a new method breaks the context of the loop. I've used 
this.

foreach (PriceRange _priceRange in priceRanges)
            {
                Action _ = (priceRange) =>
                {
                ...
                elem.click((e) =>
                    {
                        console.log(priceRange);
                    });
                };
                _(_priceRange);
            }

Original comment by krunosla...@gmail.com on 14 Oct 2013 at 11:07

GoogleCodeExporter commented 8 years ago
I see, that's cool, although I would usually simply create an extension ForEach 
method, which gives out a bit cleaner syntax:

public static void ForEach<T>(this IJsArrayEnumerable<T> list, JsAction<T> 
action)
{
   //you know what goes here... :-)
}

In any case you're right about the issue, it's a known limitation, and should 
be added as one and fixed.

Original comment by DanelK...@gmail.com on 16 Oct 2013 at 9:44