Ember.js: Is it possible to inject a dependency on a specific Route/Controller Mixin?

StackOverflow https://stackoverflow.com/questions/22656234

  •  21-06-2023
  •  | 
  •  

Вопрос

Let's say I have a SessionManager instance which I want to be accessible in every Route extending my ProtectedRoute Mixin, is it possible to inject this dependency into a "group of routes" as I can reference a single Route instance?

So instead of:

App.inject('route:protected1', 'sessionManager', 'session_manager:main');
App.inject('route:protected2', 'sessionManager', 'session_manager:main');
....

I could do something like

App.inject('route:protectedmixin', 'sessionManager', session_manager:main);
Это было полезно?

Решение

You certainly can, but it might involve a bit of juggling. You could define any logic to decide what to inject and where if you want to rely on the default conventions you could manually find this objects and then use the fullname when injecting.

Another option would be to do it for each route, regardless of whether they include the Mixin or not. Inject doesn't need the full name, if you call `App.inject('route', ...) it would work by default.

If going with option one, it would look something like this. You basically need to find those routes implementing their mixins and then inject into all of those.

var guidForMixin = Ember.guidFor(App.YourMixin);
var routesToInjectInto = Ember.keys(App).filter(function (key) { 
  var route, mixins;
  if (key.match(/Route$/))
    route = App[key];
    mixins = Ember.meta(route).mixins;
    if (mixins) {
      !!mixins[guidForMixin];
    }
    return false; 
);
routesToInjectInto.each( function (key) {
  var keyForInjection = Ember.decamelize(key);
  App.inject('route:' + keyForInjection, 'sessionManager', 'session_manager:main');
});

Also I would suggest doing all of this inside an initializer, but that might be a minor consideration.

Ember.onload('Ember.Application', function(Application) {
   Application.initializer {
    name: "sessionManager"
    initialize: function (container, application) {
      // do the above here. Refer to app as the namespace instead of App. 
      // use the container instead of App.__container__ to register. 
    };
});
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top