简体   繁体   中英

jquery vs google closure ajax

I've been looking into the google closure library for ajax calls, and I've gone through an example that looks like:

goog.events.listen(request, "complete", function(){
  if (request.isSuccess()) {
    // do something cool
   } else {
     // display an apologize message
   }
});

As opposed to a jquery example that looks something like:

$.ajax({url: url, success: function () { }, error: function () { }});

I've been seeing google closure popup a lot more, but what would be the advantage or disadvantage in this case? The jquery library calls just seem a lot simpler for ajax related calls like this one.

Your Closure sample is incomplete. I assume just before your sample you created an XhrIo instance and called send() on it.

If you want a simpler Closure equivalent to the jQuery sample you posted you can use the static XhrIo.send() . It would look something like this:

goog.net.XhrIo.send(
  url,
  function(event) {
    var xhr = event.target;
    if (xhr.isSuccess()) {
      // do something cool
    } else {
      // display an apologize message
    }
  });

That's admittedly clunkier than the jQuery version. In general, Closure is designed with object-oriented programming in mind (in stark contrast to jQuery which is mostly static functions). This may suit you or not, depending on whether you prefer to write your JS code in an object-oriented way.

In this particular case you might get a small advantage out of Closure if you create an XhrIo object that you reuse for multiple requests (eg, you can setTimeoutInterval() on it to be used for all requests). If you care about memory, Closure may also give you more explicit control over garbage collection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM