jquery deferred

jquery 的延迟调用

by yakun chen

HTML

<form id="ajax-form" action="" method="get">
    <fieldset>
        <div class="text">
            <label for="title">Search</label>
            <input type="text" id="title" name="s" />
        </div>
        <div class="actions">
            <button type="submit">Request</button>
        </div>
    </fieldset>
</form>
<div id='response'><div/>

JavaScript

$(document).ready(function() {
  var $ajaxForm = $('#ajax-form'),
      $response = $('#response'),
      noresults = 'There were no search results.',
      failed = 'Sorry, but the request could not ' +
        'reach its destination. Try again later.',
      api = {};

  var buildItem = function(item) {
    var title = item.name,
        args = [],
        output = '<li>';

    if (item.type == 'method' || !item.type) {
      if (item.signatures[0].params) {
        $.each(item.signatures[0].params, function(index, val) {
          args.push(val.name);
        });
      }
      title = (/^jQuery|deferred/).test(title) ? title : '.' + title;
      title += '(' + args.join(', ') + ')';
    } else if (item.type == 'selector') {
      title += ' selector';
    }
    output += '<h3><a href="' + item.url + '">' + title + '</a></h3>';
    output += '<div>' + item.desc + '</div>';
    output += '</li>';

    return output;
  };

  var response = function(json) {
    var output = '';
    if (json && json.length) {
      output += '<ol>';
      $.each(json, function(index, val) {
        output += buildItem(val);
      });
      output += '</ol>';
    } else {
      output += noresults;
    }

    $response.html(output);
  };

  $ajaxForm.on('submit', function(event) {
    event.preventDefault();

    $response.empty();

    var search = $('#title').val();
    if (search == '') {
      return;
    }

    $response.addClass('loading');

    // 进行缓存
    if (!api[search]) {
      api[search] = $.ajax({
        url: 'http://book.learningjquery.com/api/',
        dataType: 'jsonp',
        data: {
          title: search
        },
        timeout: 15000
      });
    }
    api[search].done(response).fail(function() {
      $response.html(failed);
    })
    .always(function() { // be called either resolved or rejected.
      // always 不论成功与失败
      $response.removeClass('loading');
    });
  });
});