Skip to content Skip to sidebar Skip to footer

Overriding Backbone.view Delegateevents So The Events Object Can Include Mobile Events

I am using Hammer.js to capture touchscreen events in a Backbone View. Hammer has a special syntax for adding touch listeners, which I have been using in the View's initialize func

Solution 1:

This jsbin shows how it is possible to override the default Backbone View logic for delegateEvents.

You can easily extend it as needed to handle Hammer.JS as you had above to extend Backbone to support the various touch events.

I needed to copy the value of delegateEventSplitter locally as it's privately declared (within a closure) inside of the Backbone library. Only functions that were executed/returned within the context of that variable are able to access that value. Since your new class does not execute in that context, it's unable to directly access the value.

The relevant code:

varSampleView = Backbone.View.extend({
  events: {
    "click" : '_clicked' 
  },

delegateEvents: function(events) {
      if (!(events || (events = _.result(this, 'events')))) return;
      this.undelegateEvents();
      for (var key in events) {
        var method = events[key];
        if (!_.isFunction(method)) method = this[events[key]];
        if (!method) thrownewError('Method "' + events[key] + '" does not exist');
        var match = key.match(/^(\S+)\s*(.*)$/);
        var eventName = match[1], selector = match[2];
        method = _.bind(method, this);
        eventName += '.delegateEvents' + this.cid;
        if (selector === '') {
           this.$el.on(eventName, method);
        } else {
           this.$el.on(eventName, selector, method);
        }
      }  
},

  render: function() {        
     this.$el.html("hi");
     returnthis; 
  },        
  _clicked: function() {
     alert("clicked!"); 
  }
});

// assumes there's an element with an id of "content"
$(function() {
  var view = newSampleView();
  $("#content").append(view.render().$el);  
});

Post a Comment for "Overriding Backbone.view Delegateevents So The Events Object Can Include Mobile Events"