1

I have a Backbone View with events for mobile and desktop version:

events: {
  "touchstart .button": "action1",
  "mousedown  .button": "action1",
  "touchend   .button": "action2",
  "mouseup    .button": "action2",
}

I want only one of the event fired when touched from my mobile device. Currently in one of my mobile device, action1 is fired twice.

I have tried using a custom method from this solution, but somehow in Android 2.3 the custom method for touchend after touchstart won't be fired, but using pure "touchend" would be fired instead.

Thus I'm thinking if Backbone.js can prevent "mouseup" from being fired if "touchend" is being fired.

Community
  • 1
  • 1
EwyynTomato
  • 4,009
  • 1
  • 31
  • 39

3 Answers3

4

Another approach, which feels slightly less hacky to me:

I like to test for touch events and set a global variable upon initialization of the application.

MyApp.clickEvent = ('ontouchstart' in window) ? "touchstart" : "mousedown";

Then in my views I perform something like:

events: function() {
    var _events = {};
    _events[MyApp.clickEvent + " .button"] = "action1";

    return _events;
}
dehrg
  • 1,721
  • 14
  • 17
2

One hacky solution would be to use the underscore.js function throttle to make it so that the function can be called only once per x milliseconds. Check the documentation here to see if it suits your needs.

The final solution would be:

action1: _.throttle(function(params) {
    // Do what you do here
}, 400); // The timeframe within which the function can be called just once.
jakee
  • 18,486
  • 3
  • 37
  • 42
0

You can define a function to determine touch devices like:

function is_touch_device() {  
  try {  
    document.createEvent("TouchEvent");  
    return true;  
  } catch (e) {  
    return false;  
  }  
} 

then use it in events:

events: function() {
    if(is_touch_device) {
       return {
          /// touch events
       }

    } else {
      return {
        /// mouse events
      }


}
}

if they are exactly the same dehrg answer would be a less redundant one

Community
  • 1
  • 1
zarehb
  • 21
  • 7