หน้าเว็บ

วันเสาร์ที่ 29 ธันวาคม พ.ศ. 2555

call back function javascript


function Asynchronous(callback){
    this.url = "http://127.0.0.1";
    this.data = {};
    this.method = "GET";
    this.service = "test";
    /**
    * constructor define call back function 
    * if(this.callback is undefined) this.callback = function(){ }
    * else this.callback = callback
    */
    this.callback = callback || function(){ };   

    this.send = function(){
        /*
        * send data to service
        ...
        ...
        ...
        ...
        */
        var response = "hello client!"; //assume response
  
        //call callback function when send data to service success
        this.callback(response);
    }
    
    this.setData = function(data){
        this.data = data;
        return this; 
    }
    
    this.setUrl = function(url){
        this.url = url;
        return this;
    }
    
    this.setMethod = function(method){
        this.method = method;
        return this;
    }
    
    this.setService = function(service){
        this.service = service;
        return this;
    }
}
   

//example to use
new Asynchronous(function(response){
    //call back function
    console.log("response => " + response);    
})
.setMethod("GET")
.setUrl("http://127.0.0.1")
.setService("searchEbook")
.setData({
    keyWord : "pro javascript", 
    author : "redcrow", 
    edition : 2,
    limit : 25 
})
.send();

ไม่มีความคิดเห็น:

แสดงความคิดเห็น