简体   繁体   中英

How to set Instance variable after use callback function in javascript OOP

I suppose the code this :

Item.js

var item = {
    id = 0,
    itemname = "name",

    callAjax : function(){
        var ajaxdata = {itemname:this.itemname}
        MM.callajax("apiname",ajaxdata,function(data){
          //this is callback function after ajax is done
          id = data;    // suppose data = 2
        });
    },

}

MMCallajax.js

var MM = {
   callajax: function (apiname, data, callback) {

    var apiurl = this.apiBaseUrl + "/" + apiname;
    jQuery.ajax( 
               apiurl, 
               {'type': 'POST', 
                'dataType': 'json', 
                'data': data, 
                'xhrFields': { withCredentials: true }
               })
    .done(this.apiCbDone(callback))
   },

   apiCbDone : function (callback) {...},
}

I want to update id variable in item object equal data variable after use callback function

How to solve this?

Why not like this?

var item = { id: 0 };
MM.callajax("apiname",ajaxdata,function(data){
    //this is callback function after ajax is done
    item.id = data;    // suppose data = 2
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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