开发者

MooTools - Re-use Request Object

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();开发者_运维问答


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/


I don't differ with the accepted answer's point, but it actually sidesteps the question IMHO.

Take a look at the following blog post (it's not mine); there, under the subtitle Multiple Links with Request.HTML you can find some guidance about how to reuse the Request instance.

  • http://ryanflorence.com/basic-ajax-and-json-requests-with-mootools/
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜