JavaScript call to setTimeOut in dojo class

I am trying to convert JavaScript functions to a dojo class. I have setTimeOut("functionName",2000)JS in one of my methods. As I call it from a method in the decared class using the dojo.declare method. For example, below is my custom class.

    dojo.declare("Person",null,{
                    constructor:function(age,country,name,state){
                        this.age=age;
                        this.country=country;
                        this.name=name;
                        this.state=state;
                    },
                    moveToNewState:function(newState){
                        this.state=newState;
//I need to call "isStateChanged" method after 2000 ms. How do I do this?
                        setTimeOut("isStateChanged",2000);
                    },                  
                    isStateChanged:function(){
                        alert('state is updated');
                    }
                });
var person=new Person(12,"US","Test","TestState");
person.moveToNewState("NewState");

Please let me know how I can call a method isStateChangedfrom a method moveToNewStateafter 2000 ms.

+5
source share
4 answers

What you are looking for is a way to bind a value thisto a function that will call setTimeout:

moveToNewState:function(newState){
    // Remember `this` in a variable within this function call
    var context = this;

    // Misc logic
    this.state = newState;

    // Set up the callback
    setTimeout(function() {
        // Call it
        context.isStateChanged();
    }, 2000);
},     

(.: ), , Dojo "" (Prototype jQuery do). ( :. peller dojo.hitch.)

: this

+9

dojo, javascript. :

var $this = this;
setTimeout(function() { $this.isStateChanged() }, 2000);

setTimeout.

, , , ( , , , eval ed ).

+2

setTimeout(this.isStateChanged, 2000), , , . this.isStateChanged . , .

this , dojo.hitch, .

+2

dojo/_ base/lang , :

moveToNewState:function(newState){
  // Misc logic
  this.state = newState;

  // Set up the callback
  setTimeout(lang.hitch(this, function() {
    // Call with `this`
    this.isStateChanged();
  }), 2000);
}, 
+1

All Articles