Skip to content

Instantly share code, notes, and snippets.

@subimage
Created September 9, 2012 18:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save subimage/3686350 to your computer and use it in GitHub Desktop.
Save subimage/3686350 to your computer and use it in GitHub Desktop.
Sencha touch data model that fires CRUD events and can reload data from server
// Extended model that fires events on CRUD actions,
// and allows for reloading of data from the server.
Ext.define('CbMobile.model.Base', {
extend: 'Ext.data.Model',
// Overloaded methods that fire events
set: function(fieldName, value) {
this.callParent(arguments);
this.fireEvent('set', fieldName, value);
},
destroy: function() {
this.callParent(arguments);
this.fireEvent('destroy');
},
save: function(options, scope) {
this.callParent(arguments);
var action = this.phantom ? 'create' : 'update';
this.fireEvent(action);
},
// Reloads a single object's data, including assocations.
reload: function(config, scope) {
var me = this;
var proxy = me.getProxy(),
idProperty = me.getIdProperty(),
record = null,
params = {},
id = me.getId(),
callback,
operation;
scope = scope || (config && config.scope) || me;
if (Ext.isFunction(config)) {
config = {
callback: config,
scope: scope
};
}
params[idProperty] = id;
config = Ext.apply({}, config);
config = Ext.applyIf(config, {
action: 'read',
params: params
});
operation = Ext.create('Ext.data.Operation', config);
if (!proxy) {
Ext.Logger.error('You are trying to reload a model that doesn\'t have a Proxy specified');
}
callback = function(operation) {
if (operation.wasSuccessful()) {
record = operation.getRecords()[0];
me.beginEdit();
me.set(record.data);
me.endEdit(true);
me.commit();
// Have to read the raw data for associations from response,
// because it's not returned or decoded in the 'record' for some stupid reason.
var response = operation.getResponse();
var responseRawJson = Ext.JSON.decode(response.responseText);
me.handleInlineAssociationData(responseRawJson);
Ext.callback(config.success, scope, [record, operation]);
} else {
Ext.callback(config.failure, scope, [record, operation]);
}
Ext.callback(config.callback, scope, [record, operation]);
};
proxy.read(operation, callback, me);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment