I’m new to BackBone and building my app based off a template found on the web. I start by loading my data from file.json like so…
livestock.groups = Backbone.Collection.extend({
model: livestock.Activity,
url: "groups.json"
});
I then have several lines of code loading the collection to the HTML and setting button functionality. Then near the end I have a line which updates the extended collection like this…
function addToList(activity) {
livestock.groups.add({id: 6, type: activity, comments: 'Wow...that was easy.'});
}
This works fine for the HTML version of the collection but I want to add a line to addToList function that will update my .json file. How can this be done?
This isn’t actually possible. Backbone was meant to interact with a RESTful web service. When you give it the URL to a JSON file like your’e doing, it sends a
GETrequest, which works fine. It doesn’t know whether or not it called a web service or not. However, when you want to send the update to the collection, it generates an HTTPPOSTrequest. However, that doesn’t do any good submitting aPOSTrequest to a static file. Apache or whatever you’re using to host the JSON file will probably ignore that and serve the static file again.The real problem, however, is unrelated to Backbone itself. The problem is you can’t edit a file on a remote server via javascript. You need some web service in between using something like PHP or Ruby that can take the request from Backbone and update the file on the server’s hard drive.
If instead you’re developing right now on your local computer, then this won’t work for a different reason. Your browser, for security reasons, won’t allow javascript to modify local files on your hard drive, even though they’re in the same folder as your html and javascript.
Hope this helps.
Edit: Based on comments, adding links here to a couple sample adapters for Backbone to LocalStorage and IndexedDB: