This content has been marked as final.
Show 2 replies
-
1. Re: evaluate variable when attaching handler to event via element selector
Arnout Kazemier Nov 27, 2009 12:26 AM (in response to Phil_W)var myalbums = Spry.$$("#albums li"); var rows = dsAlbums.getData(); var albumid; for (var i=0;i<myalbums.length;i++) { albumid = rows[i]["albumid"]; myalbums[i].addEventListener("click", function(){ showAlbum(albumid); },false ); }Your eventlistener will use all reference to the same var albumid; not to the looped value.
What you could do is this:
var myalbums = Spry.$$("#albums li", "TabbedPanels1"), //TIP: Always specify the context for your selectors, this will speed up the selector var rows = dsAlbums.getData(); var setListener = function( element, value ){ Spry.Utils.addEventListener( element, "click", function(){ showAlbum( value ); },false ); }; for( var i = 0, length = myalbums.length; i < length; i++ ){ //TIP: always cache the length in a variable when you are looping setListener( myalbums[i], rows[i]["albumid"] ); }Hopes this helps
-
2. Re: evaluate variable when attaching handler to event via element selector
Phil_W Nov 27, 2009 11:20 AM (in response to Arnout Kazemier)Hi,
Spot on, your suggestion works as I require without modification. So I can keep my HTML nice and clean whilst still having the event listener function I require. Thanks for the tips on performance as well - not really critical here but certainly a good practice to follow.
Cheers for that - it certainly did help
Phil


