Binding events conditionally in Backbone - mobile or desktop

backbone-events, backbone.js, javascript, jquery

Solution

I think the problem might be that you're binding the events the jquery-way not the Backbone way, by using delegateEvents.

I suggest you to try the following:

if(isMobile){

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

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

}

Hope this helps.

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

I tested this out myself, you can do this in a very beautiful way!

First remove all that isMobile and delegate events crap from your initialize method, it just clutters it up! Then make the Backbone.View events hash as a function that returns an events hash (Yes, you CAN do that!)

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 voilà!

Problem

To make it easier to read i put everything under the `initialize` function. Is there something wrong here? The alert gets triggered so it's not the condition. I have the share actions hidden and would like to show them on Hover on desktop and Tap on mobile given the hover impossibility. Am I missing something here? `console.log()` doesn't throw any errors. ``` 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); } }, ... ```

Original source

Related problems