Backbone/Underscore uniqueId() Odd Numbers

2019-05-07 16:17发布

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(); });

1条回答
地球回转人心会变
2楼-- · 2019-05-07 16:50

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.

查看更多
登录 后发表回答