givanse
givanse

Reputation: 14953

How to add Ember to the onDeviceReady event in Phonegap?

In Phonegap we wait for the onDeviceReady event for our code to start executing. Following this path I added my Ember app like this:

var App = null; // Ember

var phonegap = {
    initialize: function () {
        this.bindEvents();
    },
    bindEvents: function () {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    onDeviceReady: function () {
        App = Ember.Application.create({});
        // Now I can start adding my Ember stuff, but
        // even for a tutorial app that is somewhere between
        // 100 to 200 lines and it will be harder to maintain
        // inside here. So I wrap that with a function
        // and put it outside.
        addMyEmberStuff();
    }
}

function addMyEmberStuff() {

// Ember Routes, Controllers, Views etc.
App.Router.map(function() {

});

App.IndexController = Ember.Controller.extend({
    init: function () {
        this._super();
        // device API calls
        // create/render View(?)
        // trigger DOM events etc
    }
});

}

I know that I can initialize an Ember app outside of the onDeviceReady and everything will keep working. The problem is that the index page of the app has calls to the device API and also some DOM events must occur before Ember starts working its magic.

This seems to me the proper way of doing things.

How do I solve this design for the case of a larger app where I want to have each Ember Controller/View/Template in its own file? I can't keep wrapping everything with the addMyEmberStuff function.

Upvotes: 1

Views: 1015

Answers (1)

Ryan
Ryan

Reputation: 3594

You want prevent you Ember application from starting before PhoneGap is ready. To do this you can use defer and advance readiness.

App = Ember.Application.create()
App.Post = ...
App.PostsRoute = ...
App.PostsController =  ...

App.deferReadiness();

document.addEventListener('deviceready', function() {
  App.advanceReadiness();
});

Once advanceReadiness is called Ember will begin routing for your application.

Upvotes: 7

Related Questions