Open In App

Backbone.js set Model

In this article, we will see the Backbone.js set() model. The Backbone.js set() model is used to assign or set the value to the attribute in a model. In other words, this model can be utilized to set the hash of attributes, i.e one or many attributes can be set on the model. The change event will be triggered on the model if any of the attributes change the state of the model.

Syntax:



model.set(attributes, [options]);

Parameter Values:

Example 1: In this example, we will set values to the “book” model.






<!DOCTYPE html>
<html>
  
<head>
    <script src=
            type="text/javascript">
    </script>
    <script src=
            type="text/javascript">
    </script>
    <script src=
            type="text/javascript">
    </script>    
</head>
  
<body>
    <script type="text/javascript">  
        var Books = Backbone.Model.extend();  
        var book = new Books()
  
        book.set({ bookid: 33, price:211,book_name:"php"});  
        document.write(' Values: '+JSON.stringify(book));       
    </script
</body>
</html>

Output:

Values: {"bookid":33,"price":211,"book_name":"php"}

Example 2: In this example, we will set the new values to the “book” model that has already some values.




<!DOCTYPE html>
<html>
  
<head>
    <script src=
            type="text/javascript">
    </script>
    <script src=
            type="text/javascript">
    </script>
    <script src=
            type="text/javascript">
    </script>    
</head>
  
<body>
    <script type="text/javascript">  
        var Books = Backbone.Model.extend();  
        var book = new Books({bookid:23,price:678,book_name:"css"}); 
             
        document.write(' Values: '+JSON.stringify(book)); 
        document.write("<br>"); 
  
        book.set({ bookid: 33, price:211,book_name:"php"});  
        document.write(' Values: '+JSON.stringify(book));      
    </script
</body>
</html>

Output:

Values: {"bookid":23,"price":678,"book_name":"css"}
Values: {"bookid":33,"price":211,"book_name":"php"}

Reference: https://backbonejs.org/#Model-set


Article Tags :