Often when building an Ext JS app, I will create a functioning mock-up and work out the design and most client-side issues in my mock-ups. This has a lot to do w/the environment I am working on and it gets down to the fact that it is much faster for me to work with the mock-ups than my real app. Recently I’ve been creating a utility class for my app that has constants and utility methods and one thing that is helpful for me is my “random success/fail” ajax response method. I’ve found this is a great way for me to make sure I’m handling errors everywhere in my app, whether it is through a global error handler or on each AJAX request.
My stripped down utility class looks like this (usually I have a bit more in there, such as constants, app-specific vtypes, and logging.):
Ext.define('MyApp.Util', { singleton: true, UNKNOWN_ERROR: 'An unknown error occurred', randomSuccessFail : function (u) { var random = Math.floor(Math.random()*11), url; if (random > 8) { url = './data/dne.json' } else if (random > 3) { url = u ? u : '../util/successTrue.json'; } else { url = '../util/successFalse.json'; } return url; } });
“dne.json” is a file that does not exist, so I make sure my mock-ups are handling 404s and other server errors. The other response files look like this:
//successTrue.json { "success":true, "message":"success message here, if any" } // successFalse.json { "success":false, "message":"Failure message goes here and make it a little bit longer and even longer" }
And it gets called like so in a controller:
// A method inside a controller. Ext.Ajax request, // returning default success/fail response saveUser: function() { var userDetail = this.getUserDetail(), params; if (userDetail.getForm().isValid()) { this.getDismissAlert().hide(); params = userDetail.getValues(); Ext.Ajax.request({ url: MyApp.Util.randomSuccessFail(), jsonData: params, scope: this, callback: this.saveCallback }); } }, // And here's another example, this time on a store load // and expecting a different success response loadUserIds: function () { var combo = this.getUserIdCombo(), store = combo.getStore(); store.proxy.url = MyApp.Util.randomSuccessFail('./data/userids.json'); store.load({ scope: this, callback: this.loadUserIdsCallback }); }, // Sample callback, shown here... just because saveCallback : function (options, success, response) { var responseJson, form; if (success) { responseJson = Ext.decode(response.responseText); if (responseJson.success === true) { // whatever stuff needs to happen on success this.showSuccessResults("Updates saved"); } else { this.showErrorResults(responseJson.message); } } else { this.showErrorResults(MyApp.Util.UNKNOWN_ERROR); } },
And that’s it, a helpful utility.