1/29/2009

Prototype Ajax Responders - Disabling

The Prototype Ajax API allows us to make requests to our web servers very easily. It also supports Responders that allow you to declare standard behaviors to occur before and after your Ajax calls, like show the spinning ball and dim the page and fun things like that.

The nice thing about this approach is that you don't have to worry about setting up these behaviors around your send and receive methods for each call. Instead, they just work, until you don't want them to.

I have a session timeout popup that needs to submit an Ajax request to tickle the server session stopping it from timing out. I do not want my standard behaviors occurring since this is not a modal interaction like all my other Ajax calls.

What I need to do is let my "responders" know that this is not a call that I want handled. This is my standard Ajax API that wraps the prototype call. As you can see, I am enforcing a json interface to the callback supplied by my application.

var Url = Class.create(
{
get: function(a_url, a_callback)
{
new Ajax.Request(a_url,
{
method :'get',
onSuccess : function(a_transport)
{
var json = eval(a_transport.responseText);
a_callback(a_transport, json);
}
});
}
});

The behaviors I am using are simple dimming of the background and the usual spinner image.

Ajax.Responders.register(
{
onCreate : function(a_request)
{
if (Ajax.activeRequestCount >= 1)
{
document.body.addClassName('ajax-processing');
new Popup('spinning_wait',null,
{
position: 'screen',
modal:true,
effect: 'blink'
}).show();
}
},
onComplete : function(a_request)
{
if (Ajax.activeRequestCount == 0)
{
$('spinning_wait').popup.hide();
document.body.removeClassName('ajax-processing');
}
}
});

So the problem is how do I specify, at call time, whether a specific Ajax call should be modal or not. Fortunately, the Prototype library passes the options to your Responders so that you can push in variables as you like.

To do this add your own options to your Prototype Ajax call.

new Ajax.Request(a_url,
{
my_custom_modal_option: true,
...
});

And in your handlers you can access this custom option.

onCreate : function(a_request)
{
if (a_request.options.my_custom_modal_option)
{
...
}
}

You can of coarse pass in any property name to drive any kind of behavior you like.

No comments: