问题描述:

I've monkey-patched my router to store the current route components in a session variable:

var Router = Ember.Router.extend({

customSession: Ember.inject.service('session-custom'),

location: config.locationType,

didTransition: function() {

this._super(...arguments);

this.get('customSession').set('currentEntity', this.get('currentRouteName').split('.')[0]);

this.get('customSession').set('currentDetailView', this.get('currentRouteName').split('.')[1]);

}

});

I know that this is not the cleanest of solutions, but writing the session to the console proves that at least those parameters are set.

In my controller, I'd like to listen for changes in these parameters, but somehow this does not work:

import Ember from 'ember';

import ApplicationController from './application';

export default ApplicationController.extend({

customSession: Ember.inject.service('session-custom'),

currentRouteNameChanged: Ember.observer('customSession.currentEntity', function () {

console.log("route changed");

})

});

i.e. "route changed" is never printed to the console.

This seems quite an easy fix, but I haven't been able to find a solution on SO.

Thanks!

网友答案:

Perhaps consider using an initializer to inject your session-custom service into your application’s controllers. To get there, some suggestions…

First, in the Router, and elsewhere, use the conventional, camelized short-hand to inject your service, like this:

sessionCustom: Ember.inject.service(),

...and be sure to reference sessionCustom in your code, instead of customSession.

Next, create a session-custom initializer, and inject the service into your application’s controllers:

export function initialize(application) {
  application.inject('controller', 'sessionCustom', 'service:session-custom');
}

export default {
  name: 'session-custom',
  initialize,
};

Observing route changes from the controller should now be successful:

export default Ember.Controller.extend({
  currentRouteNameChanged: Ember.observer(
    'sessionCustom.currentEntity', function() {
      console.log("CONTROLLER: ", this.get('sessionCustom.currentEntity'));
    }
  ),
});

These changes, of course, can also be observed from the service itself:

export default Ember.Service.extend({
  currentEntity: '', // <-- it's helpful to explicitly declare

  currentRouteNameChanged: Ember.observer(
    'currentEntity', function() {
      console.log("SERVICE: ", this.get('currentEntity'));
    }
  ),
});

I’ve created an Ember Twiddle to demonstrate this solution.

相关阅读:
Top