javascript - Callback for $.post cannot access this -


i'm beginner in javascript/jquery, etc. , i'm facing little problem maybe me solve. have object prototype name page , in there array , function ajax post , process answer. code looks this:

function page( url ){     this.url = url;     this.elarr = [];      this.addelem = function( elem ){         this.elarr.push( elem );     }      this.job = function(){         $.post( this.url,             {                 // data here...             },             function( data, status ){                 var decodeddata = json.parse( data );                 this.elarr[0].value = decodeddata.value; // error: elarr not defined             });     } }; 

i like: var page = new page( 'page.php' ); page.addelem( new elem ); elem prototype .value.

the php code on server side answers correctly post request. using chrome development tools, can step javascript code , decoded json answer correct. problem arises when tries access this.elarr[0] (yes, in page1, elarr[0] exists!) example, if replace bogus line hardcoded page1.elarr[0].value = decodeddata.value; works perfectly.

i know callback function asynchronous , maybe this meaningless in (it seems be!) read "closures" i'm not sure if solution problem. i'm pretty sure simple cannot figure solution limited knowledge. can me?

in ajax callback method this refers jqxhr setting object, in case can use custom context using .bind() or $.proxy()

function page(url) {     this.url = url;     this.elarr = [];      this.addelem = function (elem) {         this.elarr.push(elem);     }      this.job = function () {         $.post(this.url, {             // data here...         }, (function (data, status) {             var decodeddata = json.parse(data);             this.elarr[0].value = decodeddata.value; // error: elarr not defined         }).bind(this));     } }; 

another option use closure variable

function page(url) {     this.url = url;     this.elarr = [];      this.addelem = function (elem) {         this.elarr.push(elem);     }      var self = this; //closure variable     this.job = function () {         $.post(this.url, {             // data here...         }, function (data, status) {             var decodeddata = json.parse(data);             self.elarr[0].value = decodeddata.value; // error: elarr not defined         });     } }; 

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -