开发者

Get dynamic event ID in backbone.js

I'm messing around with backbone.js for the first time and am also new to MVC..

This sample code creates a list and each list has an anchor with the class of updateTotal . I can successfully call the updateVar function using the click a.updateTotal':'updateVar' event

My question is how can I get the ID of the clicked anchor? Typically in jQuery I have used something like $(this).attr("id"); to get the ID of the clicked element.

Thanks!

My code....

(function($){
   var Item = Backbone.Model.extend({
    defaults: {
     itemName: 'Item Name',
     itemCount: 0 
   }
});

var List = Backbone.Collection.extend({
 model: Item
});



var ListView = Backbone.View.extend({    

  el: $('body'), // attaches `th开发者_运维技巧is.el` to an existing element.

  events: {
    'click button#addItem': 'addItem',
    'click a.updateTotal':'updateVar'
  },

  initialize: function(){
    _.bindAll(this, 'render', 'addItem', 'appendItem', 'updateVar');

    this.collection = new List();
    this.collection.bind('add',this.appendItem);
    this.collection.bind('updateVar',this.updateVar);

    this.counter=0; //total added so far
    this.render();
  },

  render: function(){
    $(this.el).append('<button id="addItem">Add item</button>');
    $(this.el).append('<ul></ul>');
    _(this.collection.models).each(function(item){
     appendItem(item);
    }, this);
  },

  addItem: function(){
    this.counter++;
    var item = new Item();
    item.set({
      itemName: 'Item '+this.counter,
      itemID: 'item'+this.counter
    });
  this.collection.add(item);
  },

  appendItem: function(item){
    $('ul', this.el).append("<li>"+item.get('itemName')+" (<span id=\""+item.get('itemID')+"-counter\">"+item.get('itemCount')+"</span>) <a class=\"updateTotal\" id=\"update-"+item.get('itemID')+"\">[update]</a></li>");
  },

  updateVar: function(){
     //------------------------------------
     //I want to get the ID to use here
     //------------------------------------
  }

});

 // **listView instance**: Instantiate main app view.
 var listView = new ListView();      
})(jQuery);


the events in backbone use jquery under the hood. you can provide an eventArgs parameter to your event handler method, and get the currentTarget from it, as any other jquery callback would:

updateVar: function(e){
  var clickedEl = $(e.currentTarget);
  var id = clickedEl.attr("id");
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜