在backbone.js中获取动态事件ID

Get dynamic event ID in backbone.js

本文关键字:动态 事件 ID 获取 backbone js      更新时间:2023-09-26

我是搞乱与backbone.js第一次,也是新的MVC..

这个示例代码创建了一个列表,每个列表都有一个锚,类为updateTotal。我可以成功调用updateVar函数使用click a.updateTotal':'updateVar'事件

我的问题是如何获得点击锚的ID ?在jQuery中,我通常使用$(this).attr("id");来获取被点击元素的ID。

谢谢!

我的代码…

(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 `this.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);

events在后台使用jquery。你可以为你的事件处理程序方法提供一个eventArgs参数,并从中获得currentTarget,就像任何其他jquery回调一样:

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