实现Ajax延迟/承诺模式

时间:2015-03-31 22:49:28

标签: javascript jquery ajax asynchronous

我有一个测试用例,我想在每次发生表单字段change事件时向服务器发送请求。下面的实现按预期工作,直到我提交表单并检查任何空值(这是唯一执行的前端验证,其余的通过ajax 完成)。如果字段为空,则触发change事件,以便可以在服务器端执行验证。

在下面的示例中,我必须设置async=>false,以便每个触发器都能按预期工作。我意识到这并不理想,并且使用延迟/承诺模式可以更好地解决这个问题。

我已经使用了某些模式.promise.then但是我认为我需要使用.when方法,但我不确定如何将其用于我的部分工作示例。

我也不确定发送到服务器的请求数量。发送这么多是否可行,即:每次事件发生?

请忽略块注释,我只是将它们用于代码分离。

(function($){
var Registration= {};

/**
 * 
 * @type type
**/
Registration.fields = {};    
/**
 * 
 * @type type
**/
Registration.options = {
    cache       : false,
    type        : 'POST',
    dataType    : 'json',
    url         : SITE_URL + '/members/validateFieldOnChange',
    context     : undefined,
    data        : undefined,
    async       : false    // TODO
};
/**
 * 
 * @returns {undefined}
**/
Registration.init = function(){

    //caching
    this.Form = $('form#form-register');

    this.fields = {
        username    : this.Form.find('#username'),
        email       : this.Form.find('#email'),
        password    : this.Form.find('#password'),
    };   

    // register event handlers
    this.Form.on('change', 'input', $.proxy(this.handleEvents, this));
    this.Form.on('submit', $.proxy(this.handleEvents, this));
};
/**
 * 
 * @param {type} event
 * @returns {undefined}
**/
Registration.handleEvents = function(event){   
    var type, target 

    event.preventDefault();

    type   = event.type;
    target = event.target;

    if(type == 'change'){
        return this.handleChangeEvent(event.target);
    }

    return this.handleSubmitEvent();      
};

/**
 * 
 * @param {type} target
 * @returns {undefined}
**/
Registration.handleChangeEvent = function(target){

    this.options.context = target;

    this.options.data = { field : target.name, value : target.value}

    return this.validate();
};

/**
 * 
 * @returns {undefined}
**/
Registration.handleSubmitEvent = function(){

    // Ugly testcase if values are empty
    // TODO
    if($('#username').val() == ''){
        $('#username').trigger('change');
    }

    if($('#email').val() == ''){
        $('#email').trigger('change');
    }

    if($('#password').val() == ''){
        $('#password').trigger('change');
    }

};
/**
 * 
 * @returns {_L2.Registration@call;doAjax@call;then}
**/
Registration.validate = function(){
    return this.doAjax().then(
        $.proxy(this.handleResponse, this),
        $.proxy(this.handleError, this)
    );
};

/**
 * 
 * @param {type} response
 * @returns {undefined}
**/
Registration.handleResponse = function(response){

    var field = $(this.options.context);

    if(response.msg == 'success')
    {
        field.addClass('valid');
    }
    else
    {
        field.val('');
        field.attr('placeholder', response.responseError);
        field.addClass('invalid');
    }

    return;
};
/**
 * 
 * @param {type} error
 * @returns {undefined}
**/
Registration.handleError = function(error){
    switch(error.code)
    {
        case 404:
            return console.error('Not found');
        break;
        case 401:
            return console.error('un-authorized access!');
        break;
        case 500:
            return console.error('system error!');
        break;
    }
};

/**
 * 
 * @returns {unresolved}
**/
Registration.doAjax = function(){
    return $.ajax(this.options).promise();
}

Registration.init();
})(jQuery);

0 个答案:

没有答案
相关问题