Function

Available since v2.3.0

object
Object
An object with an owner.
returns
Object
An owner object.

Framework objects in an Ember application (components, services, routes, etc.) are created via a factory and dependency injection system. Each of these objects is the responsibility of an "owner", which handled its instantiation and manages its lifetime.

getOwner fetches the owner object responsible for an instance. This can be used to lookup or resolve other class instances, or register new factories into the owner.

For example, this component dynamically looks up a service based on the audioType passed as an argument:

audio.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import Component from '@glimmer/component';
import { action } from '@ember/object';
import { getOwner } from '@ember/application';

// Usage:
//
//   <PlayAudio @audioType={{@model.audioType}} @audioFile={{@model.file}}/>
//
export default class extends Component {
  get audioService() {
    let owner = getOwner(this);
    return owner.lookup(`service:${this.args.audioType}`);
  }

  @action
  onPlay() {
    let player = this.audioService;
    player.play(this.args.audioFile);
  }
}