Ticket #1237 (closed bug: invalid)

Opened 5 years ago

Last modified 5 years ago

Problem with variables scope/reference in box.events.register

Reported by: openlayers Owned by: euzuro
Priority: critical Milestone: 2.6 Release
Component: Events Version: 2.5
Keywords: box events register variable scope reference Cc: mnovo@…
State:

Description

We are trying to add dynamically events to box markers. Refer to  boxes.html example.

1. We notice that only border color setting works, if you try to add a popup to the box marker you will see that the last loop of the for overwrite all popups generated dynamically.

            for (var i = 0; i < box_extents.length; i++) {
                ext = box_extents[i];
                bounds = new OpenLayers.Bounds(ext[0], ext[1], ext[2], ext[3]);
                box = new OpenLayers.Marker.Box(bounds);
                box.events.register("click", box, function (e) {
                    this.setBorder("yellow");
                    // Try adding the following line (ticket problem/example 1.)
                    alert(i);
                });
                boxes.addMarker(box);
            }

2. If you re-assign a value to the variable i (for counter) after the for{}, this will overwrite all the previous popup's values.

            for (var i = 0; i < box_extents.length; i++) {
                ext = box_extents[i];
                bounds = new OpenLayers.Bounds(ext[0], ext[1], ext[2], ext[3]);
                box = new OpenLayers.Marker.Box(bounds);
                box.events.register("click", box, function (e) {
                    this.setBorder("yellow");
                    // Try adding the following line (ticket problem/example 1.)
                    alert(i);
                });
                boxes.addMarker(box);
            }
            // Try adding the following line (ticket problem/example 2.)
            i='why?';

Problems with variable addressing in the initializing of Object Events?

Attachments

boxes_problem.html Download (1.6 KB) - added by openlayers 5 years ago.
Boxes example with some lines added to demonstrate the problem/bug

Change History

Changed 5 years ago by openlayers

Boxes example with some lines added to demonstrate the problem/bug

Changed 5 years ago by crschmidt

  • status changed from new to closed
  • state Needs Discussion deleted
  • resolution set to invalid

This is not an OpenLayers bug.

See  http://www.jibbering.com/faq/faq_notes/closures.html for information on Javascript closures.

What you probably want to do is:

    for (var i = 0; i < box_extents.length; i++) {
        ext = box_extents[i];
        bounds = new OpenLayers.Bounds(ext[0], ext[1], ext[2], ext[3]);
        box = new OpenLayers.Marker.Box(bounds);
        box.i = i;
        box.events.register("click", box, function (e) {
           this.setBorder("yellow");
           alert(this.i);
        });
        boxes.addMarker(box);
    }
Note: See TracTickets for help on using tickets.