Ben Lesh
Ben Lesh

Reputation: 108471

Ember: How do I inject into a view?

Suppose I have some reusable thing:

App.FooUtil = Ember.Object.extend({
   foo: function () {
      return "bar";
   }
});

and then I register it like so:

App.register('util:fooUtil', App.FooUtil);

And I try to "inject" it into my view:

App.inject('view', 'fooUtil', 'util:fooUtil');

and now suppose I have this View:

App.SuperView = Ember.View.extend({
   contextMenu: function(evt) {
      //This is ALWAYS undefined!
      var fooUtil = this.get('fooUtil');
      window.alert(fooUtil.foo());
      event.preventDefault();
   }
});
{{#view App.SuperView}}Right Click Me!{{/view}}

I can't inject the utility class into my view at all. What gives?

banging my head against a wall, I've also tried:

App.inject('views', 'fooUtil', 'util:fooUtil');
App.inject('view:index', 'fooUtil', 'util:fooUtil');
App.inject('view:topLevel', 'fooUtil', 'util:fooUtil');
App.inject('view:super', 'fooUtil', 'util:fooUtil');

Upvotes: 1

Views: 174

Answers (1)

gordonc
gordonc

Reputation: 532

Is there a downside to injecting fooUtil into all controllers? Then Your code would look like this:

App.SuperView = Ember.View.extend({
   contextMenu: function(evt) {
      var fooUtil = this.get('controller.fooUtil');
      window.alert(fooUtil.foo());
      event.preventDefault();
   }
});

Also where are you doing the injection? I usually do it in an Initializer.

Ember.Application.initializer({

  name: 'fooUtil',
  after: 'store',

  initialize: function(container) {
    container.injection('controller', 'fooUtil', 'util:fooUtil');
  }
});

Upvotes: 2

Related Questions