什么是 jQuery 中的队列? [英] What are queues in jQuery?

查看:18
本文介绍了什么是 jQuery 中的队列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现 queue()/dequeue() 上的 jQuery.com 文档太简单了,难以理解.jQuery 中的队列到底是什么?我应该如何使用它们?

解决方案

jQuery 的使用 .queue().dequeue()

jQuery 中的

队列 用于动画.您可以将它们用于您喜欢的任何目的.它们是基于每个元素存储的函数数组,使用 jQuery.data().它们是先进先出 (FIFO).您可以通过调用 .queue() 向队列添加一个函数,并且您使用 .dequeue() 删除(通过调用)函数.>

要了解内部 jQuery 队列函数,请阅读源码 查看示例对我有很大帮助.我见过的最好的队列函数示例之一是 .delay():

$.fn.delay = 函数(时间,类型){时间 = jQuery.fx ?jQuery.fx.speeds[时间] ||时间:时间;类型 = 类型 ||"fx";返回 this.queue(类型,函数(){var elem = this;设置超时(功能(){jQuery.dequeue( elem, type );}, 时间 );});};

默认队列 - fx

jQuery 中的默认队列是 fx.默认队列有一些不与其他队列共享的特殊属性.

  1. 自动启动:调用$(elem).queue(function(){});fx队列会自动dequeue 下一个函数并在队列尚未启动时运行它.
  2. 'inprogress' sentinel: 每当你 dequeue() 一个来自 fx 队列的函数时,它就会 unshift()(推入数组的第一个位置)字符串 "inprogress" - 标记队列当前正在运行.
  3. 这是默认值! .animate() 和所有调用它的函数默认使用 fx 队列.

注意:如果您使用自定义队列,则必须手动.dequeue()函数,它们不会自动启动!

检索/设置队列

您可以通过调用不带函数参数的 .queue() 来检索对 jQuery 队列的引用.如果您想查看队列中有多少项目,可以使用该方法.您可以使用 pushpopunshiftshift 就地操作队列.您可以通过将数组传递给 .queue() 函数来替换整个队列.

快速示例:

//让我们假设 $elem 是一个 jQuery 对象,它指向我们正在制作动画的某个元素.var queue = $elem.queue();//从动画队列中移除最后一个函数.var lastFunc = queue.pop();//在开头插入:queue.unshift(lastFunc);//用队列中的前三项替换队列$elem.queue(queue.slice(0,3));

动画(fx)队列示例:

在 jsFiddle 上运行示例

$(function() {//让我们用谷歌地图做点什么: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 调整大小 = function() {//简单的动画回调 - 让地图知道我们调整了大小google.maps.event.trigger(map, 'resize');};//等待 2 秒$map.delay(2000);//调整div的大小:$map.animate({宽度:250,高度:250,左边距:250,边距顶部:250},调整大小);//地理编码$map.queue(function(next) {//找到stackoverflow的whois地址:geocoder.geocode({'address': '55 Broadway New York NY 10006'},handleResponse);函数句柄响应(结果,状态){如果(状态 == google.maps.GeocoderStatus.OK){var location = results[0].geometry.location;地图.setZoom(13);map.setCenter(location);new google.maps.Marker({地图:地图,位置:位置});}//返回地理编码器结果,继续动画:下一个();}});//在我们发现堆栈溢出后,再等 3 秒$map.delay(3000);//并再次调整地图大小$map.animate({宽度:500,高度:500,边距左:0,边距顶部:0},调整大小);});

另一个自定义队列示例

在 jsFiddle 上运行示例

var theQueue = $({});//jQuery 在一个空对象上 - 一个完美的队列持有者$.each([1,2,3],function(i, num) {//让我们向队列添加一些非常简单的函数:theQueue.queue('警报',函数(下一个){//显示一些东西,如果他们点击是",运行下一个函数.if (confirm('index:'+i+' = '+num+'
运行下一个函数?')) {下一个();}});});//创建一个按钮来运行队列:$("<按钮>", {文本:'运行队列',点击:函数(){theQueue.dequeue('警报');}}).appendTo('body');//创建一个按钮来显示长度:$("<按钮>", {text: '显示长度',点击:函数(){警报(theQueue.queue('警报').length);}}).appendTo('body');

排队 Ajax 调用:

我开发了一个 $.ajaxQueue() 使用 $.Deferred 的插件,.queue()$.ajax() 也传回 promise 在请求完成时解决.在 1.4 中仍然有效的 $.ajaxQueue 的另一个版本发布在我对 对 Ajax 请求进行排序

/** jQuery.ajaxQueue - ajax 请求队列** (c) 2011 科里·弗朗* 在 MIT 和 GPL 许可下获得双重许可.** 需要 jQuery 1.5+*/(功能($){//jQuery 在一个空对象上,我们将使用它作为我们的队列var ajaxQueue = $({});$.ajaxQueue = 函数(ajaxOpts){var jqXHR,dfd = $.Deferred(),承诺 = dfd.promise();//排队我们的ajax请求ajaxQueue.queue( doRequest );//添加中止方法promise.abort = 函数(状态文本){//如果 jqXHR 处于活动状态,则代理中止它如果(jqXHR){返回 jqXHR.abort( statusText );}//如果还没有 jqXHR,我们需要从队列中删除var queue = ajaxQueue.queue(),index = $.inArray( doRequest, queue );如果(索引> -1){queue.splice( index, 1 );}//然后拒绝延迟dfd.rejectWith(ajaxOpts.context || ajaxOpts,[承诺,状态文本,"]);回报承诺;};//运行实际查询函数 doRequest( 下一个 ) {jqXHR = $.ajax(ajaxOpts).done(dfd.resolve).fail(dfd.reject).then(下一个,下一个);}回报承诺;};})(jQuery);

<小时>

我现在已将此添加为关于 learn 的文章.jquery.com,该站点上还有其他关于队列的精彩文章,去看看吧.

I found the jQuery.com document on queue()/dequeue() is too simple to understand. What exactly are queues in jQuery? How should I use them?

解决方案

The uses of jQuery .queue() and .dequeue()

Queues in jQuery are used for animations. You can use them for any purpose you like. They are an array of functions stored on a per element basis, using jQuery.data(). They are First-In-First-Out (FIFO). You can add a function to the queue by calling .queue(), and you remove (by calling) the functions using .dequeue().

To understand the internal jQuery queue functions, reading the source and looking at examples helps me out tremendously. One of the best examples of a queue function I've seen is .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 );
  });
};

The default queue - fx

The default queue in jQuery is fx. The default queue has some special properties that are not shared with other queues.

  1. Auto Start: When calling $(elem).queue(function(){}); the fx queue will automatically dequeue the next function and run it if the queue hasn't started.
  2. 'inprogress' sentinel: Whenever you dequeue() a function from the fx queue, it will unshift() (push into the first location of the array) the string "inprogress" - which flags that the queue is currently being run.
  3. It's the default! The fx queue is used by .animate() and all functions that call it by default.

NOTE: If you are using a custom queue, you must manually .dequeue() the functions, they will not auto start!

Retrieving/Setting the queue

You can retrieve a reference to a jQuery queue by calling .queue() without a function argument. You can use the method if you want to see how many items are in the queue. You can use push, pop, unshift, shift to manipulate the queue in place. You can replace the entire queue by passing an array to the .queue() function.

Quick Examples:

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

An animation (fx) queue example:

Run example on 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);
});

Another custom queue example

Run example on 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+'
Run 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');

Queueing Ajax Calls:

I developed an $.ajaxQueue() plugin that uses the $.Deferred, .queue(), and $.ajax() to also pass back a promise that is resolved when the request completes. Another version of $.ajaxQueue that still works in 1.4 is posted on my answer to Sequencing Ajax Requests

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


I have now added this as an article on learn.jquery.com, there are other great articles on that site about queues, go look.

这篇关于什么是 jQuery 中的队列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆