Friday, January 21, 2011

Whack a bit of EXT JS

Sometimes just using an Ext JS class inside of a simple javascript is all that is required as opposed to formally extending one. In this case I want to wrap a Ext.data.store object inside a simple javascript object so I can configure it to perform all my CRUD operations.
The object will be created using a simple method intuitively named init() which will be invoked like this...

dataStore = MyStoreObject.JsonStore.init({
enterpriseId: 'acompany', // send some parameters (config options in javascript speak through the init method
screenId: 'somescreenid', // send some more config options
userId: 'arindam', // and still some more ...
id: 'someId',
root: 'root_of_json',
fields: ['field1', 'field2', 'field3'],
autoLoad: true
});


Now the object itself

MyStoreObject.JsonStore = {
init: function(config){ // all those config opts are contained in config
// constants
... some constants go here for next processing

// url pattern
... some calculations based on the constants and config (see config.enterpriseId)
var urlPattern = P18N_CONTROLLER_NAME + PATH_SEPARATOR + config.enterpriseId 
+ PATH_SEPARATOR + config.screenId + PATH_SEPARATOR + config.userId;
// setup proxy
... some more value setting etc...
var proxy = new Ext.data.HttpProxy({
api: {
read    : urlPattern + PATH_SEPARATOR + READ_FUNCTION,
create  : urlPattern + PATH_SEPARATOR + CREATE_FUNCTION,
update  : urlPattern + PATH_SEPARATOR + UPDATE_FUNCTION,
destroy : urlPattern + PATH_SEPARATOR + DELETE_FUNCTION
}
});
// setup reader
... and some more 
var reader = new Ext.data.JsonReader({
root: config.root,
fields: config.fields
});
// setup writer
... still more 
var writer = new Ext.data.JsonWriter({
encode: false
});
// setup the store
... now we create the Ext object store
var store = new Ext.data.Store({
id: 'MyStoreObject.InternalStore_' + new Date().getTime(),
restful: true,
proxy: proxy,
reader: reader,
writer: writer,
autoLoad: config.autoLoad ? config.autoLoad : false
});
... now we insert a new attribute [viz. store] into our current object (this) and assign the Ext's store to it
this.store = store;
... and return the new object. this way the callers of the init method actually get a fully configured Ext.data.Store object which they are free to use in whatever way they see fit
return store;
}
}