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 `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);
the
eventsin backbone use jquery under the hood. you can provide aneventArgsparameter to your event handler method, and get thecurrentTargetfrom it, as any other jquery callback would: