Organizing your App Cloud code

App Cloud templates can be organized in any form or fashion, with one exception: the manifest file must be at the root of the template directory. Otherwise, you can use any conventions you like.

In my templates, I like to have one JavaScript file per HTML file. For example:

template/
    html/
        news.html
        sports.html
        weather.html
    js/
        NewsView.js
        SportsView.js
        WeatherView.js
    manifest.json

My JavaScript "classes" share a lot of functionality, so I throw a base class into the mix. I also like to put third-party code in its own directory:

template/
    html/
        news.html
        sports.html
        weather.html
    js/
        lib/
            brightcove-app-cloud-1.7.3.js
            some-other-library.js
        View.js
        NewsView.js
        SportsView.js
        WeatherView.js
    manifest.json

The base View class performs common functions like loading and caching data:

function View() {
    // load a content feed from App Cloud and cache it by name
    this.loadFeed = function (name, callback, options) {
        ...
    };

    // load JSON from a URL and cache it by name
    this.loadJSON = function (name, url, callback) {
        ...
    };

    // get a cached feed by name
    this.getCachedFeed = function (name) {
        return bc.core.cache(name) || null;
    };

    // etc
}

I also hang some other static functions off the base class:

View.Banner = function (elemId, title) {
    ...
};

My individual view classes, like NewsView, derive from View:

function NewsView() {
    this.init = function () {
        ...
    };

    // etc
}

NewsView.prototype = new View();

There are other ways to model inheritance in JavaScript, but I play it straight.

As for actually doing stuff, I wait until the user enters the view for the first time before running any code:

<!-- news.html -->
<script>
var view;

$(bc).bind("viewfocus", function (evt) {
    if (!view) {
        view = new NewsView();
        view.init();
    }
});
</script>

You can see working code samples in the reference app.

p.s. Get more tips and tricks (and share your own) by joining the Brightcove App Cloud discussion group on Google.