public
Created

Custom Model for ExtJS

  • Download Gist
custom_model.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118
Ext.define("CustomRest", {
extend: 'Ext.data.proxy.Rest',
alias : 'proxy.customrest',
setAction: function(config) {
this[config.name] = function(model, options){
Ext.apply(options, {
records:[model],
record: model,
action : config.name
});
var scope = options.scope || model;
var operation = new Ext.data.Operation(options);
var callback = function(operation) {
args = [model, operation];
if (operation.wasSuccessful()) {
Ext.callback(options.success, scope, args);
} else {
Ext.callback(options.failure, scope, args);
}
Ext.callback(options.callback, scope, args);
};
return this.doRequest.apply(this, [operation, callback]);
};
this.actionMethods[config.name] = config.method || "POST";
},
getAction: function(name) {
return this.actions.filter(function(action) {
return action.name === name;
})[0];
},
pattern: /:(\w+)(?:(\(.*?\)))?(\?)?(\*)?/g,
interpolate: function(url, model) {
return url.replace(this.pattern, function(_, property) {
return model.get(property);
});
},
buildUrl: function(request) {
var url = this.callParent(arguments);
var action = this.getAction(request.action);
if(action && action.url) {
url = this.interpolate(action.url, request.operation.record) + ".json";
}
return url;
},
 
constructor: function(config) {
 
this.actions = config.actions;
this.callParent([config]);
 
if(config && config.actions) {
for(action in config.actions) {
this.setAction( config.actions[action] );
}
}
 
}
 
});
 
Ext.define('CustomModel', {
extend:'Ext.data.Model',
merge: function(fields) {
for(var field in fields) {
this.set(field, fields[field]);
}
},
constructor: function() {
this.callParent(arguments);
this.setProxy({
type: 'customrest',
url: this.url,
format: 'json',
actions: this.actions
});
 
var self = this;
if(self.actions) {
for(position in self.actions) {
var action = self.actions[position];
self[action.name] = (function(act) {
return function(options) {
self.doAction(act, options);
};
})(action.name);
}
}
},
doAction: function(action, options) {
this.getProxy()[action](this, options);
}
});
 
Ext.override(CustomModel, {
statics: {
load: function() {
this.setProxy({
type: 'rest',
url: this.prototype.url,
format: 'json'
});
this.callParent(arguments);
}
}
});
sistema.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12
Ext.define('Sistema', {
extend: 'CustomModel',
fields: ['id','nome','cliente_id'],
actions: [
{
name: "por_cliente",
method: "GET",
url: "/clientes/:cliente_id/sistemas/por_cliente"
}
],
url: "/sistemas"
});

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.