This code does not have much context, but will illustrate my question. It’s a Backbone view defined in an AMD module which I use to load via require.js
Essentially I want to be able to add events to a Backbone view after initialization has been run. At the moment I am making an empty events object, and then in a method called addView, I add an event each time the function is called. This is not currently working.
I’m not sure at what point the events are registered, but I’m suspecting that I somehow have to get the view to update it’s listeners when the events object changes?
Does anybody know how I can achieve adding events to a Backbone.js after initialization?
define([
'jQuery',
'Backbone'],
function ($, Backbone) {
var contentViews = new Array();
var SlidePanelView = Backbone.View.extend({
events: {},
/// <param name="targetDataAtt">The unique value inside the target's Data-Slide-Panel-Id attribute</param>
/// <param name="event">Backbone event to trigger view</param>
/// <param name="destroyOnRemove">True to destroy view when removed, False otherwise (Default true)</param>
addView: function (targetDataAtt, event, view, destroyOnRemove) {
destroyOnRemove = typeof destroyOnRemove !== 'undefined' ? destroyOnRemove : true;
this.events[event] = "viewEventFired";
contentViews[targetDataAtt] = { View: view, DestroyOnRemove: destroyOnRemove };
},
viewEventFired: function (e) {
var target = $(e.target);
var id = target.attr('data-slide-panel-id');
console.log(id);
}
});
// Return a singleton??
return new SlidePanelView;
});
If I’m understanding the question correctly, after you add additional events to the events hash, call delegateEvents() on the view to re-bind events.
It does unbind all the existing event bindings and rebinds all the events in the events hash again, and I’m not sure of the underlying performance issues of doing that, but its something to be aware of.