Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwriting events hash for inherited Backbone.js View

I have a Backbone View for a general element that specific elements will be inheriting from. I have event handling logic that needs to be applied to all elements, and event handling logic that is specific to child-type elements. I'm having trouble because a child View has its own callback for an event that is also handled by the parent View, and so when I try to use the events hash in both, either the child or parent callback is never called. Let me illustrate with some code:

var ElementView = Backbone.View.extend({
  events: {
    "mouseup": "upHandler",
    "mousedown": "downHandler",
    "mousemove": "moveHandler"
  },

  initialize: function() {
    // add events from child
    if (this.events)
      this.events = _.defaults(this.events, ElementView.prototype.events);

    this.delegateEvents(this.events);
  }
});

var StrokeView = ElementView.extend({
  events: {
    "mousemove": "strokeMoveHandler"
  }
});

How would I solve this in an extensible way, especially if I will later have another level of inheritance?

like image 493
troyastorino Avatar asked Dec 17 '22 04:12

troyastorino


1 Answers

One way to handle this would be to use "namespaces" for events:

var ElementView = Backbone.View.extend({
  events: {
    "mouseup.element": "upHandler",
    "mousedown.element": "downHandler",
    "mousemove.element": "moveHandler"
  },

  initialize: function() {
    // add events from child
    if (this.events)
      this.events = _.defaults(this.events, ElementView.prototype.events);

    this.delegateEvents(this.events);
  }
});

var StrokeView = ElementView.extend({
  events: {
    "mousemove.strokeview": "strokeMoveHandler"
  }
});

In fact, this approach is suggested in Backbone.js documentation.

like image 200
Arnold Zokas Avatar answered Dec 27 '22 06:12

Arnold Zokas