JoshuaDavid
JoshuaDavid

Reputation: 9519

How to share one AJAX call between two stores?

I have two Sencha/ExtJS4 grids which use the exact same data (ie, same store.proxy.url), but each uses different filters, so each has its own separate store. The problem is I am making an unnecessary AJAX call to retrieve the extra copy to work with.

What is the recommended approach to make a single AJAX call and then share the data between two stores, for independent filtering?

potential solutions:

Upvotes: 4

Views: 530

Answers (2)

Eric
Eric

Reputation: 6995

The Ext JS 4 framework seems to be built with the intention that each view receives its own store. As mentioned in other answers, your best option is to create a second store and copy all the records from one to the other.

function cloneStore(src, dest) {
    var recs = src.getRange(); // returns array of records
    dest.loadRecords(recs);  // removes existing records before batch add
}

The exact implementation of that function may vary depending on how you need your data spread out. If each grid only needs a subset of the data to begin with, you can initialize a master store from your Ajax call, then create two sub-stores using filters directly on the store.data MixedCollection.

// Note: This function isn't exactly "good practice"
// Actual implementation may vary
function populateSubStores(master, storeA, storeB) {
    var dataA = master.data.filter(/* filter criteria for store A */),
        dataB = master.data.filter(/* filter criteria for store B */);
    // dataA and dataB are MixedCollections of records
    storeA.loadRecords(dataA.getRange());
    storeB.loadRecords(dataB.getRange());
}

Or some variation thereof. This should be enough to get you started in the right direction.

If you're really gung-ho, you could create a new type of store that maintains separate MixedCollections representing filter states from different views, then return each filter state as a store with an identical interface to Ext.data.Store but with an implementation that operates on the "master" store's internal representation so that existing views can operate without overrides. But I don't recommend it.

Upvotes: 2

mik
mik

Reputation: 1575

You can create two instances of one store and then just copy data from one store to another using getRange() and add() methods. Creating two classes doesn't seem reasonable.

Upvotes: 1

Related Questions