How can I add dynamic events in my view class in Backbone.js
I have a View Class with
var myViewClass = Backbone.View.extend({
events: {
'change select': 'changeSelect',
'click a.changeLink': 'clearSelect'
},
initialize: function() {
this.delegateEvents({'click select': 'changeSelect'});
},
.
.
.
});
This is adding {'click select': 'changeSelect'} event, however somehow {'click a.changeLink': 'clearSelect'} doesn't woek.
anybody knows the solution?
Thanks, Rohan
If you inspect your console, you will see the dynamically created elements injected in your DOM. Now we can add event handlers. To attach event handlers to the dynamically created button, we need to select the button with a class of btn and add an event listener of click .
Attaching the event dynamicallyclassName = 'dynamic-link'; // Class name li. innerHTML = dynamicValue; // Text inside $('#links'). appendChild(li); // Append it li. onclick = dynamicEvent; // Attach the event!
If you create an element via document. createElement , add an event listener, and append it to the DOM. Your events will fire. If you create an element as a string like this: html += "<li>test</li>"`, the elment is technically just a string.
Right-click the control for which you want to handle the notification event. On the shortcut menu, choose Add Event Handler to display the Event Handler Wizard. Select the event in the Message type box to add to the class selected in the Class list box.
Backbone automatically delegates events from the events attribute of your view. You are overrriding the previously delegated events. You can call $(this.el).delegate(...) but you can also do
this.delegateEvents(_.extend(this.events, {'click select': 'changeSelect'}));
Since I'm doing this a lot, here is my tiny Backbone extension (based on Julien's answer and my testing):
Backbone.View.prototype.addEvents = function(events) {
this.delegateEvents( _.extend(_.clone(this.events), events) );
};
Use:
BaseResizable.View = Base.View.extend({
initialize: function() {
Base.View.prototype.initialize.call(this);
this.addEvents({
'resizestop': 'resizeStop'
});
},
resizeStop: function(event, ui){...}
}
You will have to do addEvents()
again if you use undelegateEvents()
.
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