title: How can I update all models in a collection - Backbone.js
body: <p>I am setting the <code>value</code> attribute of all models in a collection (in an <code>_.each</code> loop).  After the loop is finished, each <code>value</code> attribute is unchanged.  I believe this is because the <code>_.each</code> loop is creating a new instance variable for each model.  Is there a standard way to update models of a collection that I am not following?</p>
  
  <p>The code which should force the dice into a straight (1,2,3,4,5,6). <code>rollableDice</code> refers to a Backbone collection of Backbone models which have a <code>value</code> attribute.  This is a method on a container model:</p>
  
  <pre class="lang-js prettyprint-override"><code>makeStraight: function() {
    console.log('making straight');
    console.log(_(this.rollableDice.models).pluck('value'));
    var counter = 1;
    _(this.rollableDice.models).each(function(die) {
      console.log(die.get('value'));
      die.set('value', counter);
      console.log(die.get('value'));
      counter++;
    }); 
    console.log(_(this.rollableDice.models).pluck('value'));
  },
  </code></pre>
  
  <p>This is the output that I see on the console:</p>
  
  <pre class="lang-js prettyprint-override"><code>making straight
  [1, 1, 3, 5, 2, 1]
  undefined
  1   
  undefined
  2   
  undefined
  3   
  undefined
  4   
  undefined
  5   
  undefined
  6   
  [1, 1, 3, 5, 2, 1]
  </code></pre>
  
  <p>//EDIT
  This is the console output that I expect to see:</p>
  
  <pre class="lang-js prettyprint-override"><code>making straight
  [1, 1, 3, 5, 2, 1]
  1
  1   
  1
  2   
  3
  3   
  5
  4   
  2
  5   
  1
  6   
  [1, 2, 3, 4, 5, 6]
  </code></pre>
  
  <p>//EDIT I'm going to show the model code in response to @numbers1311407's response.  I should not be using a model method to store and access attributes.  Instead, I should use the get/set methods or defaults method (<a href="http://backbonejs.org/#Model-defaults" rel="nofollow">http://backbonejs.org/#Model-defaults</a>) even while inside the model.  <strong>This is what not to do</strong>:</p>
  
  <pre><code>var Die = Backbone.Model.extend({
    initialize: function() {
      _.bindAll(this, 'roll')
    },
  
    value: 1,
  
    roll: function() {
      this.value = _.random(1,6);
    },
  });
  </code></pre>