不使用jquery实现Deferred对象 [英] Implement Deferred object without using jquery

查看:81
本文介绍了不使用jquery实现Deferred对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在不使用jQuery的情况下实现基本的Deferred对象。在这里,我将仅实现已完成和失败的回调,具有解析和拒绝功能。和ofCourse使用此函数关联 promise 方法。

I want to implement basic Deferred object without using jQuery. Here i will be implementing only done and fail callbacks, with resolve and reject functions. and ofCourse associating promise method with this function.

我在纯js中执行以下实现(已编辑):

i am doing the following implementation in pure js (Edited) :

function Deferred() {
    var d = {};
    d.resolve = function() {
        d.done(arguments);
    }
    d.reject = function() {
        d.fail(arguments);
    }
    d.promise = function() {
        var x = {};
        x.done = function(args) {
            return args;
        }
        x.fail = function(args) {
            return args;
        }
        return x;
    }
    return d;
}


var v;

var setVal = function() {
    var d = new Deferred();
    setTimeout(function() {
        v = 'a value';
        d.resolve(this);
    }, 5000);
    return d.promise();
};

setVal().done(function() {
    console.log('all done :' + v);
});

但上面给出了错误: Object#< Object>没有方法'失败'

我知道返回的对象'd' Deferred()函数没有方法done()。如果我从 Deferred()返回d.promise,则不会有解析和拒绝函数。

I know the returned object 'd' of Deferred() function does not have method done(). And if i returns d.promise from Deferred() this will not have resolve and reject functions.

请指出我正在做什么错误来实现Deferred对象的简单目标。

Please point out what error i am making to achieve the simple objective of Deferred object.

这是我正在做的小提琴: http://jsfiddle.net/ SyEmK / 14 /

Here is the fiddle i am doing : http://jsfiddle.net/SyEmK/14/

推荐答案

function Deferred(){
  this._done = [];
  this._fail = [];
}
Deferred.prototype = {
  execute: function(list, args){
    var i = list.length;

    // convert arguments to an array
    // so they can be sent to the
    // callbacks via the apply method
    args = Array.prototype.slice.call(args);

    while(i--) list[i].apply(null, args);
  },
  resolve: function(){
    this.execute(this._done, arguments);
  },
  reject: function(){
    this.execute(this._fail, arguments);
  }, 
  done: function(callback){
    this._done.push(callback);
  },
  fail: function(callback){
    this._fail.push(callback);
  }  
}


var v;

var setVal = function() {
    var d = new Deferred();
    setTimeout(function() {
        v = 'a value';
        d.resolve(this);
    }, 5000);
    return d;
};

setVal().done(function() {
    console.log('all done :' + v);
});

这篇关于不使用jquery实现Deferred对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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