在Backbone中有条件地绑定事件 - 移动或桌面

Mar*_*hii 2 javascript jquery backbone.js backbone-events

为了更容易阅读,我把所有东西都放在了这个initialize功能之下.这里有什么问题吗?警报被触发,因此不是条件.我隐藏了共享操作,并希望在桌面上显示它们并在悬停不可能的情况下点击移动设备.我在这里错过了什么吗? console.log()不会抛出任何错误.

App.Views.Title = Backbone.View.extend({

initialize:function(){

    _.bindAll(this,"stickToTop");
    this.template = _.template($("#title").html());
    this.render();
    $(window).scroll(this.stickToTop);

    var isMobile = navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/);
    var share = this.$(".share");

    if(isMobile){

        // alert('mobile')
        share.on('click' , this.shareMobile , this);

    }else{
        // alert('not mobile')
        share.on('hover' , this.shareDesktop , this);

    }

},
...
Run Code Online (Sandbox Code Playgroud)

jak*_*kee 13

我认为问题可能是你通过使用delegateEvents来绑定事件jquery-way而不是Backbone方式.

我建议你尝试以下方法:

if(isMobile){

    // alert('mobile')
    this.delegateEvents({"click .share" : "shareMobile"});

}else{
    // alert('not mobile')
    this.delegateEvents({"hover .share" : "shareDesktop"});

}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.

-------更新-------

我自己测试了这个,你可以用非常漂亮的方式做到这一点!

首先删除所有isMobile并从初始化方法委托事件废话,它只是混乱了!然后将Backbone.View事件哈希作为返回事件哈希的函数(是的,你可以这样做!)

events: function() {
  // check for the mobility HERE!
  var isMobile = navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/);
  var events_hash = {
    // insert all the events that go here regardless of mobile or not
  };
  if (isMobile) {
    _.extend(events_hash, {"click .share": "shareMobile"});
  } else {
    _.extend(events_hash, {"hover .share": "shareDesktop"});
  }
  return events_hash;
}
Run Code Online (Sandbox Code Playgroud)

Etvoilà!