jQuery のキューとは何ですか? 質問する

jQuery のキューとは何ですか? 質問する

queue()jQuery.com の/に関するドキュメントは単純すぎて理解しにくいと思いますdequeue()。jQuery のキューとは一体何でしょうか? どのように使用すればよいでしょうか?

ベストアンサー1

jQueryの用途.queue()そして.dequeue()

キューjQueryの関数はアニメーションに使用されます。好きな目的に使用できます。要素ごとに保存される関数の配列で、jQuery.data()これらは先入先出(FIFO)です。関数をキューに追加するには、.queue()、そして関数を(呼び出すことで)削除します。.dequeue()

jQueryの内部キュー関数を理解するには、ソースを読むそして例を見ることは私にとって非常に役に立ちます。私が見たキュー関数の最も良い例の1つは.delay():

$.fn.delay = function( time, type ) {
  time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
  type = type || "fx";

  return this.queue( type, function() {
    var elem = this;
    setTimeout(function() {
      jQuery.dequeue( elem, type );
    }, time );
  });
};

デフォルトのキュー -fx

jQuery のデフォルト キューは ですfx。デフォルト キューには、他のキューと共有されない特別なプロパティがいくつかあります。

  1. 自動開始:$(elem).queue(function(){});キューを呼び出すと、キューがまだ開始されていない場合はfx自動的にdequeue次の関数が実行され、実行されます。
  2. 'inprogress' センチネル:dequeue()キューから関数を実行するたびにfx、キューが現在実行中であることを示すフラグのunshift()文字列が (配列の最初の場所にプッシュされます) 。"inprogress"
  3. これはデフォルトです。キューは、それを呼び出すすべての関数fxによってデフォルトで使用されます。.animate()

注意:カスタム キューを使用している場合は、.dequeue()関数を手動で実行する必要があります。関数は自動的に開始されません。

キューの取得/設定

関数の引数なしでを呼び出すと、jQuery キューへの参照を取得できます.queue()。キュー内の項目数を確認する場合は、 メソッドを使用できます。、、 を使用してpushpopキューunshiftshiftその場で操作できます。関数に配列を渡すと、キュー全体を置き換えることができます.queue()

簡単な例:

// lets assume $elem is a jQuery object that points to some element we are animating.
var queue = $elem.queue();
// remove the last function from the animation queue.
var lastFunc = queue.pop(); 
// insert it at the beginning:    
queue.unshift(lastFunc);
// replace queue with the first three items in the queue
$elem.queue(queue.slice(0,3)); 

アニメーション ( fx) キューの例:

jsFiddleで例を実行する

$(function() {
    // lets do something with google maps:
    var $map = $("#map_canvas");
    var myLatlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {zoom: 8, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP};
    var geocoder = new google.maps.Geocoder();
    var map = new google.maps.Map($map[0], myOptions);
    var resized = function() {
        // simple animation callback - let maps know we resized
        google.maps.event.trigger(map, 'resize');
    };

    // wait 2 seconds
    $map.delay(2000);
    // resize the div:
    $map.animate({
        width: 250,
        height: 250,
        marginLeft: 250,
        marginTop:250
    }, resized);
    // geocode something
    $map.queue(function(next) {
        // find stackoverflow's whois address:
      geocoder.geocode({'address': '55 Broadway New York NY 10006'},handleResponse);

      function handleResponse(results, status) {
          if (status == google.maps.GeocoderStatus.OK) {
              var location = results[0].geometry.location;
              map.setZoom(13);
              map.setCenter(location);
              new google.maps.Marker({ map: map, position: location });
          }
          // geocoder result returned, continue with animations:
          next();
      }
    });
    // after we find stack overflow, wait 3 more seconds
    $map.delay(3000);
    // and resize the map again
    $map.animate({
        width: 500,
        height: 500,
        marginLeft:0,
        marginTop: 0
    }, resized);
});

別のカスタムキューの例

jsFiddleで例を実行する

var theQueue = $({}); // jQuery on an empty object - a perfect queue holder

$.each([1,2,3],function(i, num) {
  // lets add some really simple functions to a queue:
  theQueue.queue('alerts', function(next) { 
    // show something, and if they hit "yes", run the next function.
    if (confirm('index:'+i+' = '+num+'\nRun the next function?')) {
      next();
    }
  }); 
});

// create a button to run the queue:
$("<button>", {
  text: 'Run Queue', 
  click: function() { 
    theQueue.dequeue('alerts'); 
  }
}).appendTo('body');

// create a button to show the length:
$("<button>", {
  text: 'Show Length', 
  click: function() { 
    alert(theQueue.queue('alerts').length); 
  }
}).appendTo('body');

Ajax 呼び出しのキューイング:

私は$.ajaxQueue()プラグインは$.Deferred.queue()、 そして$.ajax()また、約束リクエストが完了すると解決されます。1.4$.ajaxQueueでも動作する別のバージョンは、私の回答に投稿されています。Ajax リクエストの順序付け

/*
* jQuery.ajaxQueue - A queue for ajax requests
* 
* (c) 2011 Corey Frang
* Dual licensed under the MIT and GPL licenses.
*
* Requires jQuery 1.5+
*/ 
(function($) {

// jQuery on an empty object, we are going to use this as our Queue
var ajaxQueue = $({});

$.ajaxQueue = function( ajaxOpts ) {
    var jqXHR,
        dfd = $.Deferred(),
        promise = dfd.promise();

    // queue our ajax request
    ajaxQueue.queue( doRequest );

    // add the abort method
    promise.abort = function( statusText ) {

        // proxy abort to the jqXHR if it is active
        if ( jqXHR ) {
            return jqXHR.abort( statusText );
        }

        // if there wasn't already a jqXHR we need to remove from queue
        var queue = ajaxQueue.queue(),
            index = $.inArray( doRequest, queue );

        if ( index > -1 ) {
            queue.splice( index, 1 );
        }

        // and then reject the deferred
        dfd.rejectWith( ajaxOpts.context || ajaxOpts,
            [ promise, statusText, "" ] );

        return promise;
    };

    // run the actual query
    function doRequest( next ) {
        jqXHR = $.ajax( ajaxOpts )
            .done( dfd.resolve )
            .fail( dfd.reject )
            .then( next, next );
    }

    return promise;
};

})(jQuery);

これを記事として追加しました学ぶそのサイトにはキューに関する他の素晴らしい記事がありますので、ぜひご覧ください。

おすすめ記事