Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

javascript - How to bind events on dynamic generated buttons in backbone?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...