【问题标题】:backbone.js fire one of touch/mouse event on same function主干.js 在同一功能上触发触摸/鼠标事件之一
【发布时间】:2012-06-26 05:32:19
【问题描述】:

我有一个带有移动和桌面版本事件的主干视图:

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

我只希望在从我的移动设备触摸时触发其中一个事件。目前在我的一个移动设备中,action1 被触发了两次。

我曾尝试使用来自this solution 的自定义方法,但不知何故,在 Android 2.3 中,不会触发 touchstart 之后的 touchend 自定义方法,而是会触发纯“touchend”。

因此,我在想如果“touchend”被触发,Backbone.js 是否可以防止“mouseup”被触发。

【问题讨论】:

    标签: mobile backbone.js


    【解决方案1】:

    另一种方法,对我来说感觉不那么老套:

    我喜欢在应用程序初始化时测试触摸事件并设置一个全局变量。

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

    然后在我看来,我执行以下操作:

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

    【讨论】:

      【解决方案2】:

      一个 hacky 解决方案是使用 underscore.js 函数 throttle 使其每 x 毫秒只能调用一次该函数。检查文档here,看看它是否适合您的需求。

      最终的解决方案是:

      action1: _.throttle(function(params) {
          // Do what you do here
      }, 400); // The timeframe within which the function can be called just once.
      

      【讨论】:

        【解决方案3】:

        您可以定义一个函数来确定触摸设备,例如:

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

        然后在事件中使用它:

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

        如果它们完全相同,则 dehrg 答案将是一个不那么多余的答案

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-10-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多