0

I am using Backbonejs to build an app for a vehicle head unit. I wish to persist some of my models using the framework's read/write functions rather than using HTTP requests.

Looking at the documentation for the fetch method at backbonejs.org, not much is explained. I'm assuming that I will simply need to override the save() and fetch() methods.

This is working fine for save as follows:

save: function () {
    var json = this.toJSON();
    console.log('Saving model state: ' + JSON.stringify(json));
    sdk.save_json_file('my_model.json', json);
}

For fetch, I'm not exactly sure what this should look like. I've tried:

fetch: function () {
    var json = sdk.read_json_file('my_model.json');
    return json;
}

Can someone show me how to correctly do this?

Danny
  • 3,615
  • 6
  • 43
  • 58
  • 1
    You might want to consider overriding `Model#sync` instead. Overriding `save` and `fetch` will require you to replicate a lot of the internal logic of those methods, if you want the models to work consistently like other Backbone.Models. http://backbonejs.org/#Model-sync – jevakallio Feb 19 '13 at 09:45

2 Answers2

2

please try this:

fetch: function(){
    this.set(this.parse(JSON.parse(sdk.read_json_file('my_model.json'))), {});
    return this;
}
anhulife
  • 566
  • 2
  • 7
  • Is the object `sdk` and it's method `read_json_file` a real object and real method name? – Matt Mar 05 '13 at 23:38
0

In your model you need to specify url

MySampleModel = Backbone.Model.extend({
    url: 'my_model.json'

    ...
});

now if you do smething like that

var mySampleModelInstance = new MySampleModel();
mySampleModelInstance.fetch();

will try to load your json file

marbor3
  • 439
  • 3
  • 13
  • This was my first inclination as I'm specifying URLs for my other models that are persisted over HTTP. However, it turns out the file is not accessible accept through the sdk read/write functions. – Danny Feb 19 '13 at 09:24