views:

132

answers:

2

I have a three stores (Ext.data.JsonStore) inside a subclass of Ext.Window. I would like to call save() on all of these, display a wait mask until complete, and then close the window or handle an error.

Is there a way I can do this without ending up with something really messy? I was considering doing this by calling save() on the second store from within the save event on the first etc., and then cobbling something together so that I can set a callback to be called when the last store finishes saving, but this seems like I will end up with a big nested mess. So any suggestions on how to build this cleanly would be greatly appreciated.

+1  A: 

Something like :

var saveStores = function(stores) {

    if (stores.length === 0) {
        console.log("All stores saved");
    } else {
        var store = stores.pop();
        store.save({
            callback : function() {
               saveStores(stores);
            }
        });
    }
}

saveStores([store1, store2, store3]);

Sorry, no time to test - but the algo could be there.

Drasill
thanks. i think something like this will probably work. it's actually a bit more of a pain though because `save()` doesn't seem to take any arguments so you have to subscribe to the event on each store first... tedious
Tom Haigh
@Drasill: I posted an answer with my updated attempt based on this. thanks again
Tom Haigh
A: 

I've ended up using something like Drasill suggested, but it got a bit messy. I imagine it would screw up if you called it twice without waiting for the first time to finish, because of the way the events work.

var save_multiple_stores = function(stores, success, fail) {
    if (stores.length === 0) {
        if (success) {
            success();
        }
    } else {
        var store = stores.pop();

        var listeners = {}

        var unbind_listeners = function() {
           for (var evt in listeners) {
                store.un(evt, listeners[evt]);
           }
        }

        var onsuccess = function() {
            unbind_listeners();
            save_multiple_stores(stores, success, fail);
        }

        var onfail = function() {
            unbind_listeners();
            if (fail) {
                fail();
            }
        }

        store.on('save', onsuccess);
        listeners.save = onsuccess;
        store.on('exception', onfail);
        listeners.exception = onfail;

        var num_records = store.save();
        //save event will not fire if there are no changed records
        if (num_records <= 0) {
            onsuccess();
        }
    }
};
Tom Haigh
Not tested neither, but maybe a simpler solution : http://pastebin.com/zYn7xCKe . Thanks for the accept.
Drasill