ember simple auth session.addObserver示例?

时间:2016-01-05 00:35:44

标签: ember.js ember-simple-auth

看一个如何添加观察者来嵌入简单的auth会话服务数据属性的例子真是太棒了。

我目前仍处于另一个问题,但很快就会回到这个问题。

目前我在我的应用程序/ route.js中写了这个,但我在另一个问题上被阻止了,所以我不知道它是多么正确。我甚至不知道应用程序路由是否是放置此观察者的最佳位置,更不用说在beforeModel钩子中了。

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)

注意:我使用的是未记录的service.addObserver api版本,可能会有点但我提交了一个拉取请求:https://github.com/emberjs/ember.js/pull/12768

1 个答案:

答案 0 :(得分:0)

此代码为99%。我缺少的是我应该为每个data.key添加备注,而不仅仅是data,我想跟踪。这是我申请路线中的最终代码:

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