Paul Williams
Paul Williams

Reputation: 386

Why won't this simple backbone.js application not persist and read to localstorage?

I'm trying to write a simple demo application using backbone.js but am having problems saving using jeromegn's localstorage adapter. I've read his todo demo, and still fail to see what I'm missing. It's probably something simple....

This simple application found at https://github.com/paulspencerwilliams/backbone_tutorial works fine when the collection is just saved in memory, but nothing is written to localstorage.

Any ideas would be gratefully received!!

Upvotes: 0

Views: 896

Answers (1)

Josh Earl
Josh Earl

Reputation: 18351

The Backbone.localStorage plugin is a replacement for Backbone.sync, which normally handles fetching and persisting changes to the server. The sync method only fires at certain times, such as when the save method is called on a model object.

In your sample code, you're adding a model to the AddressBook collection, but that doesn't trigger a call to sync. If you call this.addressBook.create(newContact) from handleNewContact, the item shows up in Chrome's localStorage.

var AddView = Backbone.View.extend({
    // snip

    handleNewContact: function(data) {
        var inputField = $('input[name=name]');

        var newContact = new Contact;
        newContact.name = inputField.val();
        this.addressBook.create(newContact); // minor tweak here

        inputField.val('');
        router.navigate('', true);
    },

    // snip
});

I cleaned up a few other minor issues in the code while I was reading through it, so if this still fails for you let me know. I can send a pull request or something.

Upvotes: 3

Related Questions