Open In App

Backbone.js sync Model

Backbone.js sync Model is the function that the model calls every time it attempts to read or save a model to the server. When a model begins a sync with the server, a request event is emitted. If the request completes successfully you’ll get a sync event and an error event if not. 

Syntax: 



model.sync( method, model, options );

Parameters: It takes the following parameters:

Example#1: In this example, we will describe the Backbone.js sync Model with read and delete method.






<!DOCTYPE html>
<html>
  
<head>
    <title>BackboneJS Model sync</title>
    <script src=
            type="text/javascript">
    </script>
    <script src=
            type="text/javascript">
    </script>
    <script src=
            type="text/javascript">
    </script>
</head>
  
<body>
    <h1 style="color: green;">
        GeeksforGeeks
    </h1>
  
    <h3>BackboneJS Model sync</h3>
  
    <script type="text/javascript">
  
  
        var Geek = new Backbone.Model({
            id: "1001e",
            Name: "Cody"
        });
  
        Geek.sync = function (method, model) {
            document.write(`This is sync function which is 
            called for ${method} an model ` + 
                           JSON.stringify(model), '<br>');
        };
  
        Geek.fetch();
        Geek.destroy();
    </script>
</body>
  
</html>

Output:

Backbone.js sync model

Example#2: In this example we will describe the Backbone.js sync model with update method.




<!DOCTYPE html>
<html>
  
<head>
    <title>BackboneJS Model sync</title>
    <script src=
            type="text/javascript">
    </script>
    <script src=
            type="text/javascript">
    </script>
    <script src=
            type="text/javascript">
    </script>
</head>
  
<body>
    <h1 style="color: green;">
        GeeksforGeeks
    </h1>
  
    <h3>BackboneJS Model sync</h3>
  
  
  
  
    <script type="text/javascript">
        Backbone.sync = function (method, model) {
            document.write(`This is sync function which is 
            called for ${method} an model ` + 
                           JSON.stringify(model), '<br>');
        };
  
        var Geek = new Backbone.Model({
            id: "1001e",
            Name: "Cody"
        });
  
        Geek.sync = function (method, model) {
            document.write(`This is sync function which is 
            called for ${method} an model ` + 
                           JSON.stringify(model), '<br>');
        };
  
        Geek.save();
        Geek.save({ id: "1002e", Name: "zetshu" });
    </script>
</body>
  
</html>

Output:

Backbone.js sync model

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


Article Tags :