Search code examples
javascriptarraysbackbone.jsjavascript-objectsbackbone-views

Backbone remove and new view does not reset its attribute array content


I have a view on Backbone with these two attributes:

var MyBasketView = Backbone.View.extend({

    _totalCost: 0,
    _devices:  [],

and on initialize I go through an array in localStorage with several devices which I push them to the _devices array and sum their total to the _totalCost like this

var self = this;
_.each(this._cartItems, function(cartItem) {
    self._totalCost += cartItem.item.cost;
    self._devices.push(cartItem.item);
}

In my router I remove this view when I leave this page and I create this view again when I come back. The problem is that when I print the attributes in my initialize function the total cost is at 0 and the devices array still has the devices from before.

Shouldn't it be reset when I remove the view or create it with new MyBasketView()?

I can of course clean it in my initialize, but I would like to understand why this is happening and if it occurs with other Objects as well?


Solution

  • The explanation is the mostly the same as for Model.defaults (the fine prints) :

    Remember that in JavaScript, objects are passed by reference, so if you include an object as a default value, it will be shared among all instances.

    When you create new instances of your view, values are copied, including _devices that will point to the same array reference :

    var v1 = new MyBasketView();
    var v2 = new MyBasketView();
    
    v1._devices === v2._devices // true
    

    http://jsfiddle.net/nikoshr/67pr1gnk/

    and the content of that array is kept throughout the life of your MyBasketView prototype (even if the instances are destroyed).

    The simplest fix is to assign the variable in the initialize function:

    var MyBasketView = Backbone.View.extend({
        _totalCost: 0,
        initialize: function() {
            this._devices = [];
        }
    });
    

    http://jsfiddle.net/nikoshr/67pr1gnk/1/