BackboneJS-Sync Backbone.emulateJSON
Description
It is used to handle the requests encoded with application/json by setting the method to true.
Syntax
Backbone.emulateJSON=true |
Example
<!DOCTYPE html>
<head>
<title>Sync Example</title>
<script src="/?originalUrl=https%3A%2F%2Fcode.jquery.com%2Fjquery-2.1.3.min.js" type="text/javascript"></script>
<script src="/?originalUrl=https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Funderscore.js%2F1.8.2%2Funderscore-min.js" type="text/javascript"></script>
<script src="/?originalUrl=https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fbackbone.js%2F1.1.2%2Fbackbone-min.js" type="text/javascript"></script>
</head>
<body>
<script type="text/javascript">
//If web server that doesn't support Backbone's REST/HTTP approach, then turn on 'Backbone.emulateHTTP'
Backbone.emulateHTTP = true;
//If web server can't handle requests encoded as application/json, then set the 'Backbone.emulateJSON' to true
Backbone.emulateJSON = true;
//The sync() method reads and fetch the model data
Backbone.sync = function(method, model) {
document.write(method + ": " + JSON.stringify(model));
model.set('id', 1); //Set the model with id as '1'
};
//'Player' is a model name and contains the values to be displayed when you save the model
var Player = new Backbone.Model({
fname:"Sachin",
lname:"Tendulkar"
});
//The 'save()' method saves data of the model by delegating to sync() method
Player.save();
//When you save the model, it updates the model along with this value
Player.save({country: "india"});
</script>
</body>
</html>
Output
Let's carry out the following steps to see how above code works:
Save above code in backbone-emulateJSON.htm file
Open this HTML file in a browser.
Advertisements