tags:

views:

34

answers:

1

I would like to re-use a Request.JSON object, but I am not sure how. I'm looking for something like the following example:

// In initialize/constructor
this.request = new Request.JSON( {
    method : 'get'        
});

// Elsewhere
this.request.setOptions({
    url : 'http://...',
    onSuccess : onSuccess,
    onFailure : onFailure
}).send();
+2  A: 

there are going to be certain issues with this kind of approach.

if you only have the one instance handling all requests, then you need to make sure whilst a request is taking place, there is nothing else that can restart it with the new options as its asynchronous. additionally, events will stack up. every new instance that you run will addEvent onComplete/onSuccess/onFailure and they won't always be relevant. so you need to apply removeEvents() to the request instance before each run.

have a look here http://www.jsfiddle.net/dimitar/8a7LG/4/

i am not showing this as an example of how i'd write it but to see the problems that come with it. click the second link first then the first one (jsfiddle adds 2 seconds network lag) and you will see the alert from the second link's onComplete event stacked up on the first one as well. further more, for each click on link 2 you will see a new alert in addition to the old ones.

you must also consider how applicable it is to extend Request.JSON instead but it all depends on your needs.

p.s. if you go over to Request.JSONP this kind of structure may play some tricks, in particular with the callback functions being reset etc.

best of luck :)

edit here's the thing working with removeEvents so you don't get the stacking up: http://www.jsfiddle.net/dimitar/8a7LG/5/

Dimitar Christoff