How do I bind click event on dynamic generated buttons in backbone.js?
window.PackageView = Backbone.View.extend({
tagName: "div",
className: "package-template",
events:{
'click #display-nodes' : 'main', // This button is declared in my HTML code and calls main method successfully.
'click .display' : 'disp', // This is dynamic button generated with class as display
},
getAction: function(nodeId){ // Get Actions from NodeId and generate buttons
$('.nodes').append("<button>" + action.Name + "</button>"); //Generate Buttons
$(".nodes button").addClass("display");
},
disp: function(){
alert("Inside Disp Function");
},
On clicking #display-nodes
the nodes are displayed as required but .display
is not working. How do I make this button call the function?
And by the logic of things, eventListener will run the same function on that button, as on the one we created in HTML. The second way to bind events to dynamically created elements is by creating a function and running that function on the elements we’ve created. Sounds confusing?
Answer: Use the jQuery on() method. If you try to do something with the elements that are dynamically added to DOM using the jQuery click() method it will not work, because it bind the click event only to the elements that exist at the time of binding. To bind the click event to all existing and future elements, use the jQuery on() method.
If you try to bind the elements that are dynamically added to the DOM using the click () method of jQuery, this will not work, because it only binds the click event to elements that exist at the time of the “binding”. To bind the click event to all existing and future elements, use jQuery’s on () method. see the following example.
A Backbone view can receive events from dynamically generated DOM elements, through the events
property, as long as the dynamically generated DOM elements are descendants of the view's el
. The relevant code is in delegateEvents(). It uses jQuery's delegate() selector method.
The most likely reason it's not working for you is that the newly created <button>
is not a descendant of the view's el
. Am I right?
If this is the case and you want to keep the element outside of the view's el
, you can remove it from your view's events
property and delegate on another element in your view's init
method.
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