2012-07-18 46 views
2

爲了更容易閱讀,我把所有東西放在initialize函數下。 這裏有什麼不對嗎?警報被觸發,所以它不是條件。 我有隱藏的共享操作,並希望在桌面上懸停顯示它們,並在懸停不可能的情況下點擊移動設備。 我在這裏錯過了什麼嗎? console.log()不會引發任何錯誤。有條件地在Backbone - 手機或臺式機上綁定事件

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); 

    } 

}, 
... 
+0

,我想'窗口phone'從你丟失的用戶代理正則表達式http://stackoverflow.com/a/9926619/429521 – 2013-04-10 19:54:40

回答

13

我認爲問題可能是您使用delegateEvents將事件綁定到jQuery方式而非Backbone方式。

我建議你嘗試以下方法:

if(isMobile){ 

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

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

} 

希望這有助於。

------- ------- UPDATE

我測試了這一點我自己,你可以在一個非常美麗的方式做到這一點!

首先從初始化方法中刪除所有移動和委託事件廢話,它只是把它弄亂了!然後使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; 
} 

的Et瞧!

+0

太棒了!它完美地工作......我沒有在文檔中看到它。 – Maroshii 2012-07-18 12:21:55

+0

甜美。剛剛學到了新東西。如果在doc.ready之後沒有聲明視圖,則事件屬性中的項目無法正常工作。這個.delegateEvents對於骨幹來說更具代表性,然後我怎麼去解決這個問題 – 2012-07-18 12:45:49

+0

如果你想了解更多,請自己學習一些東西,看看更新吧! – jakee 2012-07-18 13:09:34

0

嗯..是你定義$共享,然後使用share.on(否$)?

+0

oohh!諾諾,這不是,複製/粘貼錯誤,它已經更新!謝謝! – Maroshii 2012-07-18 10:30:15

1

我會做這樣:

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

    events : { 
     'hover .mobile .share' : 'shareMobile', 
     'click .desktop .share' : 'shareDesktop' 
    }, 

    initialize:function(){ 

     //stuff... 

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

     if(isMobile){ 
      this.$el.addClass('mobile'); 
     }else{ 
      this.$el.addClass('desktop'); 
     } 

    } 
    //stuff 
}); 
+0

有趣的....良好的解決方法。 – Maroshii 2012-07-18 15:45:32

+0

我覺得它更具可讀性,並且與Backbone事件聲明一致。 – 2012-07-18 16:44:18

+0

但是我更喜歡@ jakee的方法,因爲所有的邏輯都發生在事件函數中,並返回對象而不會混淆初始化函數,也不會添加其他類,IMO。 – Maroshii 2012-07-18 17:29:17

相關問題