0
votes

Would be awesome to see an example of how to add an observer to ember simple auth's session service data property.

I'm currently stuck on another issue but will be coming back to this soon.

Currently I wrote this in my application/route.js, but I'm blocked on another issue, so I don't know how correct it is. I don't even know if the application route is the best place to put this observer, let alone in the beforeModel hook.

export default Ember.Route.extend({ //adds in login/logout actions
  session: Ember.inject.service('session'),
  //I also tried putting this code in a model() hook, still no luck.
  beforeModel() {
    this.get('session').addObserver('data', (sender, key, value, rev) => {
      console.log('session data addObserver fired with these arguments:', sender, key, value, rev)
    })
  },
  actions: {
    error: function(error, transition) {
      console.error('ApplicationRoute error action', arguments)
      // substate implementation when returning `true`
      return true;
    }
  }
}).extend(ApplicationRouteMixin)

Note: I'm using an undocumented version of the service.addObserver api, may get bit but I submitted a pull request regarding this: https://github.com/emberjs/ember.js/pull/12768

1
What's the use case for this? You want the observer to be triggered whenever anything in the session data changes?marcoow
yes, track all changes to session data.Devin Rhode

1 Answers

0
votes

This code is 99% there. The thing I was missing was that I should addObservers for each data.key, not just data, that I want to track. Here's my final code in my application route:

var sentData = {}
var sendToExtension = (service, key, value, rev/*ignored*/) => {
  if (value != null) console.log('value actually is defined for once!', value, 'rev:', rev)
  // It seems value is always undefined. Here we check if it's undefined or null and if 
  if (value == null && service.get(key) != null) value = service.get(key) 
  if (sentData[key] != null && sentData[key] === value) {
    console.log('already sent '+key+': '+value+', returning')
    return
  }
  sentData[key] = value
  //proceed however you want with the knowledge that the `key` has just been set to this `value
}

var haveRegisteredSessionObservers = false
export default Ember.Route.extend({ //adds in login/logout actions
  session: Ember.inject.service('session'),
  beforeModel() {
    //if we're in chrome, add session data observer to send the session data back to the extension background page
    if (window.chrome && !haveRegisteredSessionObservers) {
      applicationRouteInstance = this
      ;['data.email', 'data.user_id', 'isAuthenticated'].forEach((key) => {
        this.get('session').addObserver(key, sendToExtension)
      })
      haveRegisteredSessionObservers = true