我正在尝试将我的 JavaScript 函数转换为 dojo 类。我的一个 JS 方法中有一个 setTimeOut("functionName",2000)
。我如何从使用 dojo.declare 方法声明的类中的方法调用它。例如,下面是我的自定义类。
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");
请告诉我如何在 2000 毫秒后从 moveToNewState
方法调用 isStateChanged
方法。
最佳答案
您正在寻找的是一种将 this
值绑定(bind)到 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);
},
上面是使用闭包 来绑定(bind)上下文(参见:Closures are not complicated),这是执行此操作的常用方法。 Dojo 可能会提供一个内置函数来生成这些“绑定(bind)”回调(Prototype 和 jQuery 做的)。 (编辑:确实如此,在他下面的评论 peller 中亲切地指出了 dojo.hitch
。)
更多关于这个一般概念的信息:You must remember this
关于javascript - 在dojo类中调用JavaScript的setTimeOut,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5091959/