0

我是 BackBone 的新手,我根据在网络上找到的模板构建我的应用程序。我首先从 file.json 加载我的数据,就像这样......

    livestock.groups = Backbone.Collection.extend({
    model: livestock.Activity,
    url: "groups.json"
    });

然后,我有几行代码将集合加载到 HTML 并设置按钮功能。然后在接近尾声时,我有一条线可以像这样更新扩展集合...

    function addToList(activity) {
    livestock.groups.add({id: 6, type: activity, comments: 'Wow...that was easy.'});
    }

这适用于集合的 HTML 版本,但我想在 addToList 函数中添加一行来更新我的 .json 文件。如何才能做到这一点?

4

1 回答 1

1

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 GET request, 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 HTTP POST request. However, that doesn't do any good submitting a POST request 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:

于 2012-10-14T19:07:07.677 回答