megas
megas

Reputation: 21791

How emberjs function is invoked?

I want to understand how the function in plugin is invoked.

Here's the code snippet from discourse-adplugin

export default Ember.Component.extend({
  ...
  _initGoogleDFP: function() {
    var self = this;
    loadGoogle(this.siteSettings).then(function() {
      ...
    });
  }.on('didInsertElement'),
  ...
});

There's no mention that the _initGoogleDFP function is evidently invoking by somebody but it's somehow invokes from guts of emberjs.

What is the principles of initialising emberjs components? How _initGoogleDFP is invoking by emberjs?

Upvotes: 0

Views: 40

Answers (1)

dwickern
dwickern

Reputation: 3519

The Ember.on function (or Function.prototype.on) returns a special function with some Ember implementation details:

export default Ember.Component.extend({
  ...
  _initGoogleDFP: <some-special-function-object>,
  ...
});

Ember iterates the keys in your class definition, looking for these special objects, and eventually calls Ember.addListener('didInsertElement', yourFunction).


You should generally avoid using .on. It's confusing. If you have two .on('didInsertElement'), in which order do they get called? Who knows.

The preferred way to write your code is to override didInsertElement:

export default Ember.Component.extend({
  ...
  didInsertElement() {
    this._super(...arguments);

    var self = this;
    loadGoogle(this.siteSettings).then(function() {
      ...
    });
  }
  ...
});

If you need to call _initGoogleDFP from other places, make it a function and you can call it from didInsertElement:

export default Ember.Component.extend({
  ...
  _initGoogleDFP: function() {
    var self = this;
    loadGoogle(this.siteSettings).then(function() {
      ...
    });
  },

  didInsertElement() {
    this._super(...arguments);
    this._initGoogleDFP();
  }
  ...
});

Upvotes: 2

Related Questions