I'm writing a script to add extra smileys to the Gmail chat.
Its working partially, i'm stuck with the innerHTML.replace method @line 33
If you see, the regex in the replace method is passed using a variable. This is where the script is choking.
If i replace the variable with the actual regex, it works fine :|
views:
209answers:
2
+1
A:
Each timeout closure ends up with the latest value for the two variables, not the value for the current iteration. In the code, there's only one iteration, but I assume that's just simplified for posting. You can change it to something like:
for(var i = smileys.length-1; i >= 0; i--) {
(function(i)
{
var smileyRegex = smileys[i][0];
var smileySrc = smileys[i][1];
if(node.textContent.match(smileyRegex)) {
log('match');
window.setTimeout(function(){
log(node.innerHTML); log(node.innerHTML.replace(smileyRegex, '<img class="smiley_ext" src="'+smileySrc+'">'));
},1000);
}
})(i);
}
This way, each iteration step has its own set of variables. However, I'm not sure whether you actually need the timeout.
Matthew Flaschen
2010-05-22 14:14:09
aah, dumb me... off to change it :)
Vishal Shah
2010-05-22 14:21:35
Although this is a good point and it should be fixed, it might not be the problem in this case because `smileys` has a length of 1 so there would only be one iteration. Unless, of course, the OP has cut his code down in the pastebin sample provided.
Andy E
2010-05-22 14:22:15
Yeah Andy, i've cut down the code.And i've got it working by passing the variables to the function.It's all working fine now.Thanks a tonne Matthew =)
Vishal Shah
2010-05-22 14:25:43
Vishal Shah
2010-05-22 14:31:52
A:
Instead of
window.setTimeout(function(){
log(node.innerHTML);
log(node.innerHTML.replace(smileyRegex, '<img class="smiley_ext" src="'+smileySrc+'">'));
},1000);
Use
(function(smileyRegex, smileySrc) {
window.setTimeout(function(){
log(node.innerHTML);
log(node.innerHTML.replace(smileyRegex, '<img class="smiley_ext" src="'+smileySrc+'">'));
},1000);
})(smileyRegEx, smileySrc);
This is going to create scoped references to the values and so it wont be affected by the loop.
Sean Kinsey
2010-05-22 14:24:35