LoginSignup
28
28

More than 5 years have passed since last update.

backbone-localstorage.jsを使うとかなり簡単にデータの保存ができる

Last updated at Posted at 2012-12-26

Backbone.jsのサンプルの一つに上がってるtodos.jsを読んでみると、どうもbackbone-localstorage.jsを使えばかなり簡単にデータを保存できるらしい。

backbone-localstorage.jsとは

A simple module to replace Backbone.sync with localStorage-based persistence. Models are given GUIDS, and saved into a JSON object. Simple as that.
backbone-localstorage.js


window.TodoList = Backbone.Collection.extend({
    model: Todo,
    localStorage: new Store("todos"), // これ
    // ...
});

で、使い方としては件のtodos.jsだと


    initialize: function() {
      this.input    = this.$("#new-todo");

      Todos.bind('add',   this.addOne, this);
      Todos.bind('reset', this.addAll, this);
      Todos.bind('all',   this.render, this);

      Todos.fetch();
    },

こんな感じで初期化処理のときに保存してるtodoをロードしたり、


 createOnEnter: function(e) {
      var text = this.input.val();
      if (!text || e.keyCode != 13) return;
      Todos.create({text: text});
      this.input.val('');
    },

こんな感じでデータをlocalStorageにcreateしたりしている模様。

28
28
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
28
28