¿No sería más fácil crear un constructor base especializado desde Backbone.View que maneje la herencia de eventos en la jerarquía?
BaseView = Backbone.View.extend {
# your prototype defaults
},
{
# redefine the 'extend' function as decorated function of Backbone.View
extend: (protoProps, staticProps) ->
parent = this
# we have access to the parent constructor as 'this' so we don't need
# to mess around with the instance context when dealing with solutions
# where the constructor has already been created - we won't need to
# make calls with the likes of the following:
# this.constructor.__super__.events
inheritedEvents = _.extend {},
(parent.prototype.events ?= {}),
(protoProps.events ?= {})
protoProps.events = inheritedEvents
view = Backbone.View.extend.apply parent, arguments
return view
}
Esto nos permite reducir (fusionar) los eventos en la jerarquía cada vez que creamos una nueva 'subclase' (constructor hijo) utilizando la función de extensión redefinida.
# AppView is a child constructor created by the redefined extend function
# found in BaseView.extend.
AppView = BaseView.extend {
events: {
'click #app-main': 'clickAppMain'
}
}
# SectionView, in turn inherits from AppView, and will have a reduced/merged
# events hash. AppView.prototype.events = {'click #app-main': ...., 'click #section-main': ... }
SectionView = AppView.extend {
events: {
'click #section-main': 'clickSectionMain'
}
}
# instantiated views still keep the prototype chain, nothing has changed
# sectionView instanceof SectionView => true
# sectionView instanceof AppView => true
# sectionView instanceof BaseView => true
# sectionView instanceof Backbone.View => also true, redefining 'extend' does not break the prototype chain.
sectionView = new SectionView {
el: ....
model: ....
}
Al crear una vista especializada: BaseView que redefine la función de extensión, podemos tener subvistas (como AppView, SectionView) que quieran heredar los eventos declarados de su vista principal, simplemente hágalo extendiendo desde BaseView o uno de sus derivados.
Evitamos la necesidad de definir programáticamente nuestras funciones de eventos en nuestras subvistas, que en la mayoría de los casos necesitan referirse explícitamente al constructor padre.