简体   繁体   English

如何在JS中实现连锁?

[英]How to realize a chain in JS?

I know that we can use "return this" in object, eg: 我知道我们可以在对象中使用“返回此值”,例如:

var $ = {
   name : function(){
     alert("John");
     return this;
  },
  age  : function(){
     alert(21);
     return this
  }
}

$.name().age()

When one function is completed next one will be called. 一个功能完成后,将调用下一个功能。 But in JQuery there is such construction: 但是在JQuery中有这样的构造:

 $.get(url).done(callback).fail(callback);

How it works? 这个怎么运作? How: method "get" gets callback on time. 方法:方法“ get”按时获取回调。 Ajax request is async by default. 默认情况下,Ajax请求是异步的。

PS I am interested in realization without $.Defferred object. PS我对没有$ .Defferred对象的实现感兴趣。

Thanks. 谢谢。

Here's how $.get(url).done(callback); 这是$.get(url).done(callback); works. 作品。

$.get() returns an object. $.get()返回一个对象。 It returns that object immediately as soon as the async ajax call has been started (it does not wait until the ajax calls finishes). 一旦异步ajax调用开始,它将立即返回该对象(它不会等到ajax调用完成之后)。 That object has a number of methods which includes the jQuery promise methods. 该对象有许多方法,其中包括jQuery Promise方法。 One of those methods is .done() . 这些方法之一是.done() When you call .done(callback) on that returned object it stores the callback in a list of callbacks in that returned object. 当您对返回的对象调用.done(callback)时,它将回调存储在该返回的对象的回调列表中。

When the $.get() function finishes sometime later, it then .resolves() it's own promise which ends up looking for all the .done() callbacks stored in the object and calls the callbacks one at a time. $.get()函数在稍后的某个时间完成时,它随后将.resolves()作为自己的承诺,最终将查找存储在对象中的所有.done()回调,并一次调用一个回调。

So, in this sequence of events, .done() is actually called immediately right after $.ajax() finishes initiating the ajax call, but all .done() does when it executes is store the callback for use later by $.ajax() when the async operation finishes. 因此,在此事件序列中, .done()实际上在$.ajax()完成启动ajax调用后立即被调用,但是.done()在执行时所做的所有操作都是存储回调,供$.ajax()稍后使用$.ajax()当异步操作完成时。

Whether you know it or not, when you use the $.get(url).done(callback) construction, you are using a jQuery promise object and the promise API. 无论您是否知道,当您使用$.get(url).done(callback)构造时,都在使用jQuery Promise对象和Promise API。 It works pretty simply here because $.get() creates the promise object for you (and returns it and will then .resolve() or .fail() it later) and all you have to do is specify .done() , .fail() or .then() callbacks and most of the work is done for you. 它在这里非常简单,因为$.get()为您创建了promise对象(然后返回它,然后.resolve().resolve().fail() ),而您要做的就是指定.done() .fail().then()回调,大部分工作已为您完成。 You don't have to manually create a deferred object or promise object - you can just use the one returned by the ajax call. 您不必手动创建一个延迟对象或Promise对象-您只需使用ajax调用返回的对象即可。


Here's a little async queue that supports chaining for visual effects with it's own .done() handler: http://jsfiddle.net/jfriend00/tS8G3/ 这是一个异步队列,它通过自己的.done()处理程序支持视觉效果的链接: http : //jsfiddle.net/jfriend00/tS8G3/

function domWrapper(elem) {
    if (!(this instanceof domWrapper)) {
        return new domWrapper(elem);
    }
    if (typeof elem === "string") {
        elem = document.getElementById(elem);
    }
    this.elem = elem;
    this.q = [];
    this.timer = null;
    this.doneCallbacks = [];
}

domWrapper.prototype = {
    hide: function() {
        this.q.push({op: "hide"});
        this._exec();
        return this;
    },
    show: function() {
        this.q.push({op: "show"});
        this._exec();
        return this;
    },
    delay: function(t) {
        this.q.push({op: "delay", time: t});
        this._exec();
        return this;
    },
    done: function(fn) {
        this.doneCallbacks.push(fn);
        return this;
    },
    _exec: function() {
        var next;
        while (!this.timer && this.q.length) {
            next = this.q.shift();
            switch(next.op) {
                case "show":
                    this.elem.style.display = "block";
                    break;
                case "hide":
                    this.elem.style.display = "none";
                    break;
                case "delay":
                    var self = this;
                    this.timer = setTimeout(function() {
                        self.timer = null;
                        self._exec();
                    }, next.time);
                    break;
            }
        }
        // if all done with all pending activities
        if (!this.q.length && !this.timer) {
            // call the done callbacks
            for (var i = 0; i < this.doneCallbacks.length; i++) {
                this.doneCallbacks[i].call(this.elem);
            }
        }
    }
}

function makeBlue() {
    this.style.backgroundColor = "blue";
}

function makeBigger() {
    this.style.width = "200px";

}

domWrapper("test").done(makeBlue).done(makeBigger)
    .delay(2000).hide().delay(2000).show().delay(1000);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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