BackboneJS - Collection Sync
Description
It uses Backbone.sync to persist the state of a collection to the server.
Syntax
collection.sync(method, collection, options)
Parameters
method − It represents the CRUD operations such as create, read, update and delete.
collection − It contains a set of models to save the data in the collection.
options − It fires success or error message depending on the method succeeded.
Example
<!DOCTYPE html>
<html>
<head>
<title>Collection 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>
</head>
<body>
<script type = "text/javascript">
//The sync() method reads and fetches the model data
Backbone.sync = function(method, model) {
document.write("The state of the model is:");
document.write("<br>");
//The 'method' specifies state of the model
document.write(method + ": " + JSON.stringify(model));
};
//The 'myval' is collection instance and contains the values which are to be fetched
//in the collection
var myval = new Backbone.Collection ({
site:"TutorialsPoint",
title:"Simply Easy Learning..."
});
//The myval.fetch() method display the model's state by delegating the sync() method
myval.fetch();
</script>
</body>
</html>
Output
Let us carry out the following steps to see how the above code works −
Save the above code in the sync.htm file.
Open this HTML file in a browser.
backbonejs_collection.htm
Advertisements