Hi - I wonder if anyone can help me with something that's been bugging me for a long time. When writing JS, I try to encapsulate my code somehow. For instance, in the example below, I have a function ('testFunc') that's encapsulated within jQuery's document.ready callback function :
Code:
$(function(){
var testFunc = function(x){
x++;
return x;
}
});
If I then start using JS's base timer functions like settimeout, I've always been unsure of how to access the 'testFunc' function. As I understand it, even if the timer functions are called inside the same function, as in...
Code:
$(function(){
var testFunc = function(x){
x++;
return x;
}
var timer = setTimeout("testFunc", 100);
});
... they will lose the scope of the jQuery callback - instead the timer functions will only be able to access objects in the global scope.
Does anyone have any ideas/advice on best practise for how to solve this kind of problem?
Hi - am afraid I couldn't get that last suggestion to work. If anyone's interested however, I 'think' I've got something reasonably simple to work, using the Singleton pattern. I don't know if it's a bit over the top, but it seems to work...
Code:
var NSD = (function() {
return {
testFunc: function(x){
x++;
document.write (x);
},
onload: $(function(){
var a = setTimeout('NSD.testFunc(1)', 1000);
})
}
})();
'NSD' here is just a namespace used to encapsulate all my functions. Because 'testFunc' is now a public function (note, not a global one), the 'setTimeout' function can access it.
You can probably tell I'm just experimenting - I'm sure there are more elegant ways of doing this, so any suggestions are welcome!!
Bookmarks