Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone/Underscore uniqueId() Odd Numbers

I'm relatively new to Backbone and Underscore and have one of those questions that's not really an issue - just bugging me out of curiosity.

I built a very simple app that allows you to add and remove models within a collection and renders them in the browser. It also has the ability to console.log the collection (so I can see my collection).

Here's the weird thing: the ID's being generated are 1,3,5... and so on. Is there a reason specific to my code, or something to do with BB/US?

Here's a working Fiddle: 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(); });
like image 819
Fluidbyte Avatar asked Feb 19 '23 15:02

Fluidbyte


1 Answers

if you look in the backbone.js source code you'll notice that _.uniqueId is used to set a model's cid: https://github.com/documentcloud/backbone/blob/master/backbone.js#L194

that means that every time you create a model instance, _.uniqueId() is invoked. that's what causing it to increment twice.

like image 157
davidbrai Avatar answered Mar 07 '23 17:03

davidbrai