0

I am using Backbonejs to build an in-dash vehicle application. Some of my models persist back to a server using HTTP, and others persist to the local file system only accessible through the framework's read/write functions.

My question is specifically about those that I'm persisting to the file system, though it could probably apply to either scenario.

My Player model, which as you might have guessed handles audio playback, contains a Playlist object. When the app is closed, I am saving the current Player state to the file system so that it can be resumed the next time it is launched.

save: function () {
    sdk.write_json_file('player.json', this.toJSON());
}

I see that toJSON is automatically also calling toJSON for contained models, resulting in stored JSON that looks something like:

{
    'playing':true,
    'playlist_i': 2
    'playlist':[
        {
            'stream_url': 'http://my.stream.com/blah',
            'title': 'Title goes here',
            'artist': 'Artist goes here',
            ...& other metadata
        },
        ...and so on
    ]
}

So then I have my overridden fetch function:

fetch: function () {
    var p = sdk.read_json_file('player.js');
    this.set(this.parse(p), {});
    return this;
}

Now the problem is that once fetch is called, the reset event fires and my player view attempts to update. The player view is assuming that the player model contains a playlist object. Technically it does, but at this point the playlist is just a JavaScript hash as it has not yet been parsed into a Playlist instance.

I'm wondering where I would create the playlist instance within the model based on the data returned from the file read.

Disclaimer: Backbonejs noob

Danny
  • 3,615
  • 6
  • 43
  • 58

1 Answers1

0

I do not have enough context to try to be very specific, but anyway, if you want to write another "adapter" for Backbone, you should probably make your own Backbone.sync adapter, and override the sync method for the relevant models to use your own sync adapter.

The save/fetch methods call into the Backbone.sync adapter, but they also make sure the data is properly pre/post processed (by calling parse, which allows you to do more than just set specific members from the passed json or similar).

There are Backbone.sync adapters for localStorage, indexedDB and probably a few for the filesystem APIs as well. The first thing on Google is:

https://github.com/scotthovestadt/Backbone.fileSystem

I've successfully used adapters for localStorage and indexedDB, but haven't tried the one I linked to above myself.

Marius Kjeldahl
  • 6,830
  • 3
  • 33
  • 37