Backbone.JS Set()

The Backbone.JS Set() collection method is used to update a collection with a set of items in a model.

Syntax:

Backbone.Collection.Set ( models, options )   

Parameters:
models: This parameter is used to specify the models to be set in the collection.
options: This parameter is used to specify the parameters like id, name, etc.

Example:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<title>Example</title>
<script src="https://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js" type="text/javascript"></script>
<script type="text/javascript">
var num = Backbone.Model.extend({
defaults: {
number: 1
} });
var X = Backbone.Collection.extend({
model: num
});
var num1 = new num({number: 2});
var num2 = new num({number: 3});
var numCollection = new X();
numCollection.add([num1,num2]);
numCollection.set([num1, {number: 5}]);
document.write(JSON.stringify(numCollection.toJSON()));
</script>[{"number":2},{"number":5}]
<title>Example</title> <script src="https://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js" type="text/javascript"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min.js" type="text/javascript"></script> <script type="text/javascript"> var num = Backbone.Model.extend({ defaults: { number: 1 } }); var X = Backbone.Collection.extend({ model: num }); var num1 = new num({number: 2}); var num2 = new num({number: 3}); var numCollection = new X(); numCollection.add([num1,num2]); numCollection.set([num1, {number: 5}]); document.write(JSON.stringify(numCollection.toJSON())); </script>[{"number":2},{"number":5}]
  

  
Example  
  
  
  
  
  
[{"number":2},{"number":5}]  
  
  

Output:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
[{"number":2},{"number":5}]
[{"number":2},{"number":5}]
[{"number":2},{"number":5}]

Explanation:
In the above example, the Set() method update the ‘num1’ model by passing the value in the collection.