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;
});
Backbone. js trigger Event is used to invoke or callback the function for the given event or a space-delimited list of events. The subsequent arguments will be passed along to the event callbacks in order to trigger it.
Backbone. Backbone has been around for a long time, but it's still under steady and regular development. It's a good choice if you want a flexible JavaScript framework with a simple model for representing data and getting it into views.
Backend Synchronization BackboneJS is use with the front-end and back-end systems, allows the synchronization with the backend to provide support to RESTful APIs.
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.
addView: function (targetDataAtt, event, view, destroyOnRemove) {
destroyOnRemove = typeof destroyOnRemove !== 'undefined' ? destroyOnRemove : true;
this.events[event] = "viewEventFired";
this.delegateEvents();
contentViews[targetDataAtt] = { View: view, DestroyOnRemove: destroyOnRemove };
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With