PDA

View Full Version : How to handle repeative callbacks?



thedott
15 Nov 2010, 7:32 AM
I have several Ajax calls in my app and most of them require the same callback functions for success and failure responses. I want to consolidate these functions for maintenance purposes. What's the best way to accomplish this?

Here's what I'm trying to accomplish; however the parameters are undefined:
(A better question: how do I reference an anonymous function definition if possible?)



// App File ...
Ext.ns('App');

App.form = function() {
return {
onSuccess: function(form, action) {
if (action.result.success == false) {
Ext.Msg.alert('Save', action.result.msg);
return;
}
},

onFailure: function(form, action) {
Ext.Msg.alert('Error', 'Form submission failed.');
}
}
}

// Separate file ...
myForm.getForm().submit({
success: App.form.onSuccess,
failure: App.form.onFailure,
});
Thanks!

laurentParis
15 Nov 2010, 9:06 AM
first


App.form = function() {
onSuccess: function(form, action) {...


syntaxe error !

thedott
15 Nov 2010, 10:08 AM
The only error I see is that I didn't copy my code correctly over to the forum (see "return { ... }" above).

Screamy
15 Nov 2010, 10:19 AM
I'm not sure if this is what you're after, but you can globally handle all Ajax related calls for success and/or failure as shown below. This works for form.getForm().submit() as well as Ext.Ajax.request():



Ext.Ajax.on("requestcomplete", ajaxRequestHandler, this);
Ext.Ajax.on("requestexception", ajaxRequestHandler, this);
Where the ajaxRequestHandler function would be something like:


function ajaxRequestHandler(connection, response, options)
{
// Serverside blowup...
if (response.status == undefined) {
// examine response.responseText for serverside error message, show
// user an error dialog.
}
// HTTP STATUS 'OK'
if (response.status == 200) {
// success response, do nothing.
}
else {
if (response.status == 403) {
// show Access Denied message.
} else if (response.status == 404) {
// show Page Not Found
}
else (etc...) {
// whatever else is important to handle...
}
}
}
I like using one handler method, but you can obviously have a separate success and failure handler.

thedott
15 Nov 2010, 11:52 AM
Thanks, this will work but isn't quite how I wanted to organize my code. I was hoping to get my original method above working, but somehow I lose scope between defining the success/failure callback in the submit function and the actual success/failure function definition. Unfortunately, I'm not well versed in JavaScript yet to find a work-around (... if it's even possible).

darthwes
15 Nov 2010, 12:06 PM
myForm.getForm().submit({
success: App.form.onSuccess,
failure: App.form.onFailure,
scope: App.form
});

Is that what you want?

thedott
15 Nov 2010, 12:24 PM
Thanks! That's what I want. Evidently, I have a poor understanding of the scope parameter.