no Deferreds - don’t cry!

Yesterday on an Extjs project I had a rather big module with some store dependencies to load before my controller allows the user to start working.

I refused to load all stores one after another so I was seeking for anything like a multiple store loader to synchronize my ajax requests. Used to Deferreds from jQuery I missed something like that (fantasy code):

Extjs.when([
    this.getUsersStore().load(),
    this.getPermissionsStore.load()
]).then(
    Ext.bind( this.doSomethingAfterAllStoresAreLoaded, this )
);

But sadly you have to help yourself. To get around that “missing Deferreds” issue I did the following:

Ext.define("controller.foo", {
    
    stores: [
        /**
         * @method getUsersStore
         */
        'Users',
        /**
         * @method getPermissionsStore
         */
        'Permissions',
        // ...
    ],
    _dependencies : null,
    // some stores 
    init : function () {
        this._dependencies = [
            this.getUsersStore(),
            this.getPermissionsStore()
        ];
        this.loadStores();
    },
    loadStores : function() {
        var me = this;
        Ext.each( this._dependencies, function( store ) {
            store.on( "load", me.checkDependencyLoaded, me, { single : true });
            store.load();
        });
    },
    checkDependencyLoaded : function( store, recs, success ) {
        if( ! success ) {
            // raise your error
            // you may want to check against store instance to get an unique error
        }
        var key = Ext.Array.indexOf( this._dependencies, store );
        if(  -1 != key ) {
            this._dependencies.splice( key, 1 );
        }
        if( this._dependencies.length < 1 ) {
            // stores are loaded - finished multiple requests
            // e.g. fire open module here
        }
    },
    // ..
}

Please note, that this is not real world code.