I'm trying to request a variable declared globally inside of the touchmove function but I'm getting a reference error. Does anybody know what's wrong?
function drawer(pulltab,drawer){
$('#pulltab').on('touchstart',function(e){
notworking=e.originalEvent.touches[0].pageX;
})
$(drawer).on('touchmove',function(loc){
var fingerloc=loc.originalEvent.touches[0].pageX;
var dist=fingerloc-notworking;
console.log(dist);
if (dist<0){
$(this).css('margin-left',dist);
}
})
$(drawer).on('touchend',function(){
$(this).css('transition','margin-left .1s');
$(this).css('margin-left',0);
})
}
drawer('#pulltab','#navigation-drawer');
I'm trying to request a variable declared globally inside of the touchmove function
There are no global variable declarations in your quoted code.
Assuming you haven't declared it, then you are creating (but not declaring) a global variable in the touchstart
handler on #pulltab
:
notworking=e.originalEvent.touches[0].pageX;
That uses The Horror of Implicit Globals * to create a global. But the global won't exist until that code runs.
Clearly, your touchmove
handler on drawer
is firing before your touchstart
handler on #pulltab
. Since there is no existing global called notworking
, you can't read its value, and you get a ReferenceError
. If the touchstart
on #pulltab
had executed first, you wouldn't.
Don't rely on the horror of implicit globals. Declare your variables. If you want it to be global, put
var notworking;
...outside all functions. (Although global variables are a Bad Thing™ best avoided; if you only use notworking
within the drawer
function and you don't need it shared between calls to drawer
, just declare it within drawer
.) You might also want to check, when using it, whether it has a useful value.
* (that's a post on my anemic little blog)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.