如何在Ember.js中使用HTML5本地存储?

Tar*_*ski 13 html5 local-storage ember.js

我想在我的Ember.js中使用HTML5 Local Storage.

没有Ember Data,我无法找到任何这样做的例子.

该怎么做?我需要考虑什么?

int*_*xel 22

所以我们假设我们有一个对象Storage,在我们的实际实现中,它代表了一个类似于适配器的对象,localStorage用于存储和检索数据:

App.Storage = Ember.Object.extend({
  init: function() {
    this.clearStorage();

    var items = ['foo', 'bar', 'baz'];
    localStorage.items = JSON.stringify(items);
  },
  find: function(key) {
    // pseudo implementation
    if( !Ember.isNone(key) ) {
      var items = [];
      var storedItems = JSON.parse(localStorage[key]);
      storedItems.forEach(function(item){
        items.pushObject(item);
      });
      return items;
    }
  },
  clearStorage: function() {
    // pseudo implementation
    localStorage.clear();
  }
});
Run Code Online (Sandbox Code Playgroud)

除了伪实现之外,你可以看到有一个虚拟数组,在对象初始化时存储了一些数据,稍后我们将在IndexRoute model钩子中使用它来检索它,只是为了表明这是有效的.

现在更好的东西,你可以在应用程序准备就绪之后直接执行register&inject,但是如果我们希望它在应用程序初始化时已经可用呢?好吧"有一个ember-feature for that",称为Application.initializer初始化程序,是一个简单的类,带有'name'属性和一个initialize函数,你可以访问你的应用程序container并完成需要完成的任务,让我在代码中解释一下:

时通知应用程序开始加载,我们可以听的onLoad事件来创建我们的初始化类,将registerinject之前提到的Storage对象到每一个控制器和每一个路线:

Ember.onLoad('Ember.Application', function(Application) {
 // Initializer for registering the Storage Object
  Application.initializer({
    name: "registerStorage",
    initialize: function(container, application) {
      application.register('storage:main', application.Storage, {singleton: true});
    }
  });
 // Initializer for injecting the Storage Object
  Application.initializer({
    name: "injectStorage",

    initialize: function(container, application) {
      application.inject('controller', 'storage', 'storage:main');
      application.inject('route', 'storage', 'storage:main');
    }
  });
});
Run Code Online (Sandbox Code Playgroud)

现在,由于Storage对象被注入到每个路径和每个控制器中,我们终于可以在IndexRoute model钩子中访问它并通过调用self.get('storage').find('items')我们的模板来使上面提到的存储数组可用(只是添加了一个承诺,使它实际上符合使用ember-way和一些虚拟延迟,而不仅仅是返回数组):

App.IndexRoute = Ember.Route.extend({
  model: function(){
    var self = this;
    var promise = new Ember.RSVP.Promise(function(resolve) {
      Ember.run.later(function() {
        var data = self.get('storage').find('items');
        console.log(data);
        resolve(data);
      }, 1000);
    });

    return promise;
  }
});
Run Code Online (Sandbox Code Playgroud)

在我们的index模板中,我们现在可以在虚拟数组上进行无限循环,而不是关注它来自何处:

<script type="text/x-handlebars" id="index">
  <h2>Index</h2>
  <ul>
    {{#each item in model}}
      <li>Item: {{item}}</li>
    {{/each}}
  </ul>
</script>
Run Code Online (Sandbox Code Playgroud)

最后,您可以在一个工作示例中看到以上所有内容:http://jsbin.com/eqAfeP/2/edit

希望能帮助到你.