user3467349
user3467349

Reputation: 3191

Javascript Scope and this.Variable

So I have some javascript with the following (pseudo) structure. How do I set the this.last_updated variable of the parent function from the showUpdates function, without specifically referencing the name assignment (my_main_function).

var my_main_function = new main()

function main() {
 this.last_updated; 

 function showUpdates(data){
 //set this.last_updated=

 // do Stuff
 }
 this.updateMain(){
  $.ajax({
                 url:"/my_url/"
                 type:"POST",
                 datatype:"json",
                 data: {'last_updated':this.last_updated },
                 success : function(data) { showUpdates(data)},
                 error : function(xhr,errmsg,err) {
                 alert(xhr.status + ": " + xhr.responseText); },
    });
 }
}

Upvotes: 1

Views: 86

Answers (1)

t.niese
t.niese

Reputation: 40882

Updated the code base one the comments:

There are two way of creating objects.

If you need to create the object multiple time you will do it like this:

var YourDefintinon = function() {
};

YourDefintinon.prototype.foo = function() {

};

obj1 = new YourDefintinon();
obj2 = new YourDefintinon();

obj1.foo();

If you only need it once in your code you can just do it like that:

var obj = {

};

obj.foo = function() {

};

foo();

So your would need the main only once your code would look like this:
Using Function.prototype.bind (and its polyfill for older browsers) to bind the showUpdates to the obj.

var main = {
  last_updated : null
};

function showUpdates(data){
  this.last_updated = data.update_time;
}

main.updateMain = function () {
  //<< bind showUpdates  to `this` and save the bound function in the local variabel showUpdates
  var showUpdates = showUpdates.bind(this); 

  $.ajax({
     url:"/my_url/"
     type:"POST",
     datatype:"json",
     data: {'last_updated':last_updated },
     success : showUpdates, //<< uses the showUpdates variable not the function
     error : function(xhr,errmsg,err) {
       alert(xhr.status + ": " + xhr.responseText);
     },
  });
};

As you don't want to make showUpdates accessible to others you could wrap the whole block into a function that is immediatly called:

var main = (function() {
  var main = {
    last_updated : null
  };

  function showUpdates(data){
    this.last_updated = data.update_time;
  }

  main.updateMain = function () {
    var showUpdates = showUpdates.bind(this); 

    $.ajax({
       url:"/my_url/"
       type:"POST",
       datatype:"json",
       data: {'last_updated':last_updated },
       success : showUpdates,
       error : function(xhr,errmsg,err) {
         alert(xhr.status + ": " + xhr.responseText);
       },
    });
  };

  return main;
}());

Upvotes: 1

Related Questions