开发者

event.target.id as undefined ? Creating dynamic buttons using backbone.js

I have a section element with id = wrapper. In my router I add .delegate() jQuery method to delegate events to dynamically created buttons (as traditional events:{"click button" : "gotoSomeMethod"} is not working for me).

 $(document).ready(function() {
 window.App = new window.Routers.Package;
 Backbone.history.start();              

   $('#wrapper').delegate("button", "click", function(ev){
      alert ($(ev.target).id); 
   });
});

Here is my view,

window.Views.Actions = Backbone.View.extend({
tag: 'nav',

initialize: function() {
    _.bi开发者_开发百科ndAll(this, 'render', 'gotoNode');


},

render:function(){
    this.model.each(function(action){
        var buttonTemplate = "<button id = '"  + action.toNodeId + "'>" + action.name + "     </button>";
        $(this.el).append(buttonTemplate)
    }, this);


    console.log(this.el); // when I do this I get `<div><button id = 'something'></button></div>`
    return this;
},

   events:{
      "click button":"gotoNode"  
   },

   gotoNode:function() {
     alert("inside gotoNode");  
   },

});

So the first issue here is why I get undefined as an for id? Secondly, how do I make backbone to call gotoNode() method?


The jQuery function $ returns a jQuery object, not the DOMElement. If you want to access the id of that element you need to use $(ev.target).attr("id"). Also you shouldn't use ev.target. It returns the DOMElement that was clicked and it can be the button, but it can also be the TextNode inside the button. In the second case you won't have the id attribute. What you need to use is $(this).attr("id").

For the gotoNode part, it would make more sense if you where doing the event binding in your view (move the delegate call inside your initialize method).

initialize : function () {
     _.bindAll(this, 'render', 'gotoNode');

    var self = this;

    $('#wrapper').delegate("button", "click", function(ev){
        self.gotoNode();
    });
}


If you want gotoNode() method to work you must place your button into this.el. Only then delegate will work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜