H1D
H1D

Reputation: 758

Catch app 'ready' event outside the app

I need to run some code after ember application got initialized. I don't want to invoke this code from App.ready to avoid tight coupling. It would be nice to have something like this:

App.on 'ready, -> console.log('do stuff')

But it won't work since Em.Application object is not subscribable and ready isn't really an event despite that docs said so

Upvotes: 2

Views: 752

Answers (2)

sly7_7
sly7_7

Reputation: 12011

An other possibility may be to invoke your code from the resolve callback of the application.

App.then(function(app) {
  console.log("App is resolved, so it's ready");
});

example stolen from @intuitivepixel ;) http://jsbin.com/AdOVala/66/edit

Edit/Note:

App.then() has been deprecated, see http://emberjs.com/deprecations/v1.x/#toc_code-then-code-on-ember-application:

As part of the Ember.DeferredMixin deprecation, using .then on an Ember.Application instance itself has been deprecated.

You can use the ready hook or initializers to defer/advance readiness instead.

Upvotes: 2

intuitivepixel
intuitivepixel

Reputation: 23322

A simple way you can achieve this would be to extend your Application class with the Ember.Evented mixin:

App = Ember.Application.createWithMixins(Ember.Evented, {
  ready: function() {
    console.log('App ready');
    this.trigger('appReady');
  }
});

And you hook inside the ready event inside your app and trigger your custom event using this.trigger(...)

At this point you can use .on(...) to be notified when the event is triggered.

App.on('appReady', function() {
  console.log('App already ready');
});

Example demo.

Hope it helps.

Upvotes: 6

Related Questions