Monday, January 26, 2015

Using Ember Data as a simple "cookie" method

For a recent Ember web app, I needed to store a count for how many times a certain event happened. I needed this count to persist across sessions, and I began to think back to the Todo MVC Ember tutorial I had once gone through. In the tutorial, items in a todo list were saved using Ember Data and a local storage adapter. After doing a little research, I decided this would be an appropriate way for me to approach this task. If you aren't already using Ember Data, download the js file. In addition to Ember Data, I went to Emberjs.com to find the link to the local storage adapter that was used in the tutorial. You can find it here. In order to use it, you need to tell your application that you are using it in your application.js file.
App.ApplicationAdapter = DS.LSAdapter.extend({
  namespace: 'example-emberjs'
});
To keep track of my count, I created an object called Cookie to store my count. This object must extend DS.Model in order to work with the Ember data store. I simply store one variable in the object, numberToCount.
App.Cookie = DS.Model.extend({
  numberToCount: DS.attr('number')
});
In order get my count as soon as the app was starting, I overrode the ApplicationRoute, which I was not yet doing. The only thing I do here, is call the updateCount function on my controller.
App.ApplicationRoute = Ember.Route.extend({

  setupController: function(controller, model) {
    this._super(controller,model); 
    controller.send('updateCount');
  }

});
And in my ApplicationController, I implemented an updateCount function. What I am doing here is using built in Ember Data functions to find all cookie objects, of which there should be zero or one in my case. If there are zero cookie objects, it means I haven't created one yet, so I do so, and set the numberToCount to 0. If there is a cookie object, then I increment the numberToCount field. In both cases, I save the cookie object, then set a variable "myCount" on the application controller, so that the count is accessible from all my other controllers.
  updateCount: function() {
    var self = this;
    self.store.find('cookie').then(function (cookies) {
      var cookie;
      if(cookies.content.length > 0) {
        cookie = cookies.content[0];
      } else {
        cookie = null;
      }
      
      if(cookie == null) {
        cookie = self.store.createRecord('cookie', {
          numberToCount: 0,
        }); 
      } else {
        cookie.set("numberToCount", cookie.get("numberToCount") + 1);
      }
      cookie.save();
      self.set("myCount", cookie.get("numberToCount"));
    });
    
  }
And there you have it, a simple way to persist a "cookie" across application sessions.

No comments:

Post a Comment