Christopher DuBois
Christopher DuBois

Reputation: 43440

Converting Backbone's Todo List example from localStorage

I have been looking at the Todo list example (source) for Backbone.js. The code uses local storage, and I wanted to try and convert it so that it operated via a RESTful webservice.

Suppose the webservice already exists at the route todos/. I figured I need to add in a url piece into Backbone.Model.extend and remove the localStorage: new Store("todos") line when we perform Backbone.collection.extend.

  window.Todo = Backbone.Model.extend({

    url : function() {
      return  'todos/'+this.id;
    }

    // Default attributes for a todo item.
    defaults: function() {
      return {
        done:  false,
        order: Todos.nextOrder()
      };
    },

    // Toggle the `done` state of this todo item.
    toggle: function() {
      this.save({done: !this.get("done")});
    }

  });

What is the proper way to do this?

Upvotes: 4

Views: 2198

Answers (2)

moose56
moose56

Reputation: 119

I would leave the model as it is in the Todos example. In the collection class add this property:

window.TodoList = Backbone.Collection.extend({
    ...     
    url: '/todos',
    ...
}

Calling fetch() on the collection should retrieve a list of Todo objects.

If you are using Rails you need to set ActiveRecord::Base.include_root_in_json = false otherwise Backbone.js will not be able to pull out the Todo objects from the returned json.

Upvotes: 0

Ivan Ivanic
Ivan Ivanic

Reputation: 3054

Url should be set in Collection, if you have need for diferent urls than those created by collection than declare url in model.

You need to remove

  <script src="../backbone-localstorage.js"></script> 

from index.html since it is linked after backbone.js and effectively overrides Backbone's sync method to store in localStorage.

Upvotes: 2

Related Questions