code

jQuery의 큐란 무엇입니까?

starcafe 2023. 5. 13. 10:26
반응형

jQuery의 큐란 무엇입니까?

com 에서 .com .queue()/dequeue()너무 단순해서 이해할 수 없습니다. 무엇입니까?Query의 큐는 정확히 무엇입니까?그것들을 어떻게 사용해야 합니까?

jQuery의 용도 및

jQuery의 큐는 애니메이션에 사용됩니다.원하는 용도로 사용할 수 있습니다.를 사용하여 요소별로 저장된 함수 배열입니다.그들은 선입선출(FIFO)입니다.를 호출하여 대기열에 기능을 추가할 수 있으며 를 사용하여 기능을 제거할 수 있습니다.

내부 jQuery 큐 기능을 이해하려면 소스를 읽고 예제를 보는 것이 큰 도움이 됩니다.제가 본 대기열 기능의 가장 좋은 예 중 하나는 다음과 같습니다.

$.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으로 queue가 됩니다.dequeue대기열이 시작되지 않은 경우 다음 기능을 실행합니다.
  2. '진행 중' 보초병:당신이 언제든지dequeue()fx줄을 서라, 그렇게 될 것입니다.unshift()의 첫 로 이동) (어레의첫위번이동로치) "inprogress"현재 실행 중인 대기열 플래그입니다.
  3. 기본값입니다!fx는 됩니다..animate()기본적으로 호출하는 모든 함수입니다.

참고: 사용자 지정 대기열을 사용하는 경우 수동으로 수행해야 합니다..dequeue()기능이 자동으로 시작되지 않습니다!

대기열 검색/설정

를 호출하면 jQuery 큐에 대한 참조를 할 수 ..queue()함수 인수 없이.대기열에 있는 항목 수를 확인하려면 이 방법을 사용할 수 있습니다.사용할 수 있습니다.push,pop,unshift,shift대기열을 조정할 수 있습니다.을 어이를에전대체바수있꿀습다니기에 수 ..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 호출 대기:

요청이 완료되면 해결되는 약속을 전달하기 위해 , 를 사용하는 플러그인을 개발했습니다.의 다른 버전$.ajaxQueueAjax Requests 시퀀싱에 대한 답변에 1.4에서 여전히 작동합니다.

/*
* 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);

저는 이제 이것을 학습에 관한 기사로 추가했습니다.jquery.com , 그 사이트에는 대기열에 대한 다른 훌륭한 기사들이 있습니다. 가서 보세요.

큐 방식을 이해하려면 jQuery가 애니메이션을 어떻게 하는지 이해해야 합니다.여러 애니메이션 메서드 호출을 차례로 작성하는 경우 jQuery는 '내부' 대기열을 만들고 이 대기열에 메서드 호출을 추가합니다.그런 다음 애니메이션 통화를 하나씩 실행합니다.

다음 코드를 고려합니다.

function nonStopAnimation()
{
    //These multiple animate calls are queued to run one after
    //the other by jQuery.
    //This is the reason that nonStopAnimation method will return immeidately
    //after queuing these calls. 
    $('#box').animate({ left: '+=500'}, 4000);
    $('#box').animate({ top: '+=500'}, 4000);
    $('#box').animate({ left: '-=500'}, 4000);

    //By calling the same function at the end of last animation, we can
    //create non stop animation. 
    $('#box').animate({ top: '-=500'}, 4000 , nonStopAnimation);
}

'queue'/'dequeue' 메서드는 이 '애니메이션 큐'를 제어합니다.

기본적으로 애니메이션 큐의 이름은 'fx'입니다.큐 방법을 사용하는 방법을 설명하는 다양한 예제가 있는 샘플 페이지를 만들었습니다.

http://jsbin.com/zoluge/1/edit?html,output

위 샘플 페이지 코드:

$(document).ready(function() {
    $('#nonStopAnimation').click(nonStopAnimation);

    $('#stopAnimationQueue').click(function() {
        //By default all animation for particular 'selector'
        //are queued in queue named 'fx'.
        //By clearning that queue, you can stop the animation.
        $('#box').queue('fx', []);
    });

    $('#addAnimation').click(function() {
        $('#box').queue(function() {
            $(this).animate({ height : '-=25'}, 2000);
            //De-queue our newly queued function so that queues
            //can keep running.
            $(this).dequeue();
        });
    });

    $('#stopAnimation').click(function() {
        $('#box').stop();
    });

    setInterval(function() {
        $('#currentQueueLength').html(
         'Current Animation Queue Length for #box ' + 
          $('#box').queue('fx').length
        );
    }, 2000);
});

function nonStopAnimation()
{
    //These multiple animate calls are queued to run one after
    //the other by jQuery.
    $('#box').animate({ left: '+=500'}, 4000);
    $('#box').animate({ top: '+=500'}, 4000);
    $('#box').animate({ left: '-=500'}, 4000);
    $('#box').animate({ top: '-=500'}, 4000, nonStopAnimation);
}

이제 여러분은 제가 왜 이 줄을 귀찮게 해야 하는지 물으실 수 있습니다.보통은 그렇지 않습니다.하지만 제어하고 싶은 복잡한 애니메이션 시퀀스가 있다면 큐/디큐 방법이 친구입니다.

또한 복잡한 애니메이션 시퀀스를 만드는 것에 대한 jQuery 그룹의 흥미로운 대화를 보십시오.

http://groups.google.com/group/jquery-en/browse_thread/thread/b398ad505a9b0512/f4f3e841eab5f5a2?lnk=gst

애니메이션 데모:

http://www.exfer.net/test/jquery/tabslide/

아직 질문이 있으면 저에게 알려주세요.

대기열에서 여러 개체 애니메이션

다음은 대기열에 있는 여러 개체 애니메이션의 간단한 예입니다.

Jquery를 사용하면 하나의 객체에 대해서만 큐를 만들 수 있습니다.하지만 애니메이션 기능 내에서 우리는 다른 물체에 접근할 수 있습니다.이 예제에서는 #box1 및 #box2 객체를 애니메이션화하면서 #q 객체를 통해 큐를 구성합니다.

큐를 함수의 배열로 생각합니다.따라서 큐를 배열로 조작할 수 있습니다.푸시, 팝, 언시프트, 시프트를 사용하여 큐를 조작할 수 있습니다.이 예에서는 애니메이션 큐에서 마지막 기능을 제거하고 처음에 삽입합니다.

작업이 완료되면 dequeue() 기능으로 애니메이션 큐를 시작합니다.

jsFiddle에서 보기

html:

  <button id="show">Start Animation Queue</button>
  <p></p>
  <div id="box1"></div>
  <div id="box2"></div>
  <div id="q"></div>

js:

$(function(){

 $('#q').queue('chain',function(next){  
      $("#box2").show("slow", next);
  });


  $('#q').queue('chain',function(next){  
      $('#box1').animate(
          {left: 60}, {duration:1000, queue:false, complete: next}
      )
  });    


  $('#q').queue('chain',function(next){  
      $("#box1").animate({top:'200'},1500, next);
  });


  $('#q').queue('chain',function(next){  
      $("#box2").animate({top:'200'},1500, next);
  });


  $('#q').queue('chain',function(next){  
      $("#box2").animate({left:'200'},1500, next);
  });

  //notice that show effect comes last
  $('#q').queue('chain',function(next){  
      $("#box1").show("slow", next);
  });

});

$("#show").click(function () {
    $("p").text("Queue length is: " + $('#q').queue("chain").length);

    // remove the last function from the animation queue.
    var lastFunc = $('#q').queue("chain").pop();
    // insert it at the beginning:    
    $('#q').queue("chain").unshift(lastFunc);

    //start animation queue
    $('#q').dequeue('chain');
});

CSS:

        #box1 { margin:3px; width:40px; height:40px;
                position:absolute; left:10px; top:60px; 
                background:green; display: none; }
        #box2 { margin:3px; width:40px; height:40px;
                position:absolute; left:100px; top:60px; 
                background:red; display: none; }
        p { color:red; }  

애니메이션을 큐에 넣을 수 있습니다.예를 들어, 이것 대신에.

$('#my-element').animate( { opacity: 0.2, width: '100px' }, 2000);

이것은 요소를 퇴색시키고 동시에 폭을 100px로 만듭니다.대기열을 사용하면 애니메이션을 준비할 수 있습니다.그래서 하나는 다른 하나를 따라 끝납니다.

$("#show").click(function () {
    var n = $("div").queue("fx");
    $("span").text("Queue length is: " + n.length);
});

function runIt() {
    $("div").show("slow");
    $("div").animate({left:'+=200'},2000);
    $("div").slideToggle(1000);
    $("div").slideToggle("fast");
    $("div").animate({left:'-=200'},1500);
    $("div").hide("slow");
    $("div").show(1200);
    $("div").slideUp("normal", runIt);
}
runIt();

http://docs.jquery.com/Effects/queue 의 예

이 스레드는 제 문제에 많은 도움을 주었지만, 저는 $.queue를 다른 방식으로 사용했고 제가 생각해낸 것을 여기에 게시할 것이라고 생각했습니다.필요한 것은 일련의 이벤트(프레임)가 트리거되지만 동적으로 구축되는 것이었습니다.자리 표시자의 수는 다양하며, 각 자리 표시자에는 애니메이션 이미지 시퀀스가 포함되어야 합니다.데이터는 배열로 저장되므로 배열을 순환하여 각 자리 표시자에 대한 각 시퀀스를 다음과 같이 구성합니다.

/* create an empty queue */
var theQueue = $({});
/* loop through the data array */
for (var i = 0; i < ph.length; i++) {
    for (var l = 0; l < ph[i].length; l++) {
        /* create a function which swaps an image, and calls the next function in the queue */
        theQueue.queue("anim", new Function("cb", "$('ph_"+i+"' img').attr('src', '/images/"+i+"/"+l+".png');cb();"));
        /* set the animation speed */
        theQueue.delay(200,'anim');
    }
}
/* start the animation */
theQueue.dequeue('anim');

이것은 제가 도착한 스크립트의 단순화된 버전이지만, 원칙을 보여주어야 합니다. - 큐에 함수가 추가되면 함수 생성자를 사용하여 추가됩니다. - 이렇게 하면 루프의 변수를 사용하여 동적으로 함수를 작성할 수 있습니다.함수가 다음() 호출에 대한 인수를 전달하고 이 인수가 마지막에 호출되는 방식을 기록합니다.이 경우 함수는 시간 종속성이 없습니다($.fade를 사용하지 않음).in 또는 그와 유사한 것)을 사용하여 $.delay를 사용하여 프레임을 비틀어 봅니다.

언급URL : https://stackoverflow.com/questions/1058158/what-are-queues-in-jquery

반응형