Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

javascript scope problem when lambda function refers to a variable in enclosing loop

First question on stackoverflow :) Hope I won't embarrass myself...

I have a javascript function that loads a list of albums and then it creates a list item for each album. The list item should be clickable, so I call jQuery's click() with a function that does stuff. I do this in a loop. My problem is that all items seem to get the same click function, even though I try to make a new one that does different stuff in each iteration. Another possibility is that the iteration variable is global somehow, and the function refers to it. Code below. debug() is just an encapsulation of Firebug's console.debug().

function processAlbumList(data, c) {
 for (var album in data) {
  var newAlbum = $('<li class="albumLoader">' + data[album].title + '</li>').clone();
  var clickAlbum = function() {
   debug("contents: " + album);
  };
  debug("Album: " + album + "/" + data[album].title);
  $('.albumlist').append(newAlbum);
  $(newAlbum).click(clickAlbum);
 }
}

Here is a transcript of what it prints when the above function runs, after that are some debug lines caused by me clicking on different items. It always prints "10", which is the last value that the album variable takes (there are 10 albums).

Album: 0/Live on radio.electro-music.com
Album: 1/Doodles
Album: 2/Misc Stuff
Album: 3/Drawer Collection
Album: 4/Misc Electronic Stuff
Album: 5/Odds & Ends
Album: 6/Tumbler
Album: 7/Bakelit 32
Album: 8/Film
Album: 9/Bakelit
Album: 10/Slow Zoom/Atomic Heart
contents: 10
contents: 10
contents: 10
contents: 10
contents: 10

Any ideas? Driving me up the wall, this is. :)

/Stefan

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to introduce another scope, such as like this:

var clickAlbum = (function (a) {
    return function () {
        debug("contents: " + a)
    };
})(album);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...