This is the function I use to bind ‘tap’ event on mobile devices. Basically a normal function.
bindTapEvent: function(container, selector, run, bindClickAlso){
var startX, startY, currentX, currentY = 0;
var moved = false;
var self;
if(touchDevice){
container.on({
click: function(e){
e.preventDefault();
},
touchstart: function(e){
e.preventDefault();
self = $(this);
startX = e.originalEvent.touches[0].pageX;
startY = e.originalEvent.touches[0].pageY;
},
touchmove: function(e){
currentX = e.originalEvent.touches[0].pageX;
currentY = e.originalEvent.touches[0].pageY;
if(Math.abs(startX - currentX) > 10 || Math.abs(startY - currentY) > 10){
moved = true;
}
},
touchend: function(e){
e.preventDefault();
run();
}
},
selector
)
} else {
if(bindClickAlso != false){
container.on('click', selector, function(){
run();
});
}
}
}
I make use of it like this:
tt.bindTapEvent(container, '.showColumns', function(){
container.find('.column').addClass('visible');
$(this).doSomething();
});
The only problem is that I cannot (obviously) user $(this) inside somtething like this. I’ve read about jQuery $.proxy that changes the context, but I cannot get to understand it so I can use it. Is it possible (in my case) to change the context of the anonymous function used in tt.bindTapEvent to that when I use $(this) it is ‘stored’ and ‘used’ only in the bindTapEvent function?
Take a look at .call() and .apply() which let you pass the desired context as the first parameter.
http://odetocode.com/blogs/scott/archive/2007/07/05/function-apply-and-function-call-in-javascript.aspx
so in your example instead of
run()you could userun.call(this);so you’re passing this as the context for the callback function.