where to introduce deferred function in my code

时间:2015-11-12 10:50:52

标签: javascript jquery

I have object with validate property and that property function send request to server to test.

    //clsAjax.js file where i access request function
    request: function(cmd, callback){
        _sendReq(cmd, callback);
    }



//Definition
    obj = {
        title : 'name',
        validation : function(this){
            this.valid = false;
            clsAjax.request('duplicate', function(){
                if(response == true){
                    this.valid = true;
                    console.log(this.valid);
                }
           });
       }
    }



//function call
    form.validation(obj);
    console.log(obj.valid); // It always have false value

validation function receive true but before that it executed validation false line.

I want it to wait till ajax finish execution.

How to do that??

Thank.

1 个答案:

答案 0 :(得分:0)

Two problems in your code.

1. this generally refers to object to which a function was assigned

So if you do this:

var obj = {num: 1234, func: function() {console.log(this);}};
obj.func();

You get this output:

image description

And it works same with your function:

clsAjax.request('duplicate', function(){...});

There are two workarounds:

  1. Create reference to this before creating the callback:

    var _this = this;
    clsAjax.request('duplicate', function(){_this.valid = true;});
    
  2. Use HTML5 Function.prototype.bind - that changes meaning of this in a function:

    var callback = function(){this.valid = true;}.bind(this);
    clsAjax.request('duplicate', callback);
    

1. There is no point to query the value before the callback has returned

form.validation(obj);
console.log(obj.valid); // It always have false value

When you do console.log(obj.valid) your callback wasn't called yet because it's still communicating with the server.