I'm relatively new to Backbone and Underscore, and I have one of those questions that really isn't a problem - it just annoys me out of curiosity.
I created a very simple application that allows you to add and remove models within a collection and display them in a browser. It also has a console.log collection option (so that I can see my collection).
Here's the weird thing: the generated ID is 1,3,5... and so on. Is there a reason specific to my code or something in common with BB / US?
Fiddle works here: http://jsfiddle.net/ptagp/
And the code:
App = (function(){ var AppModel = Backbone.Model.extend({ defaults: { id: null, item: null } }); var AppCollection = Backbone.Collection.extend({ model: AppModel }); var AppView = Backbone.View.extend({ el: $('#app'), newfield: $('#new-item'), initialize: function(){ this.el = $(this.el); }, events: { 'click #add-new': 'addItem', 'click .remove-item': 'removeItem', 'click #print-collection': 'printCollection' }, template: $('#item-template').html(), render: function(model){ var templ = _.template(this.template); this.el.append(templ({ id: model.get('id'), item: model.get('item') })); }, addItem: function(){ var NewModel = new AppModel({ id: _.uniqueId(), item: this.newfield.val() }); this.collection.add(NewModel); this.render(NewModel); }, removeItem: function(e){ var id = this.$(e.currentTarget).parent('div').data('id'); var model = this.collection.get(id); this.collection.remove(model); $(e.target).parent('div').remove(); }, printCollection: function(){ this.collection.each(function(model){ console.log(model.get('id')+': '+model.get('item')); }); } }); return { start: function(){ new AppView({ collection: new AppCollection() }); } }; }); $(function(){ new App().start(); });
source share