Ste*_*ven 5 javascript dojo settimeout
我正在尝试将我的JavaScript函数转换为dojo类.我在我的setTimeOut("functionName",2000)一个JS方法中.如何使用dojo.declare方法从decared类中的方法调用它.例如,下面是我的自定义类.
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");
Run Code Online (Sandbox Code Playgroud)
请告诉我如何在2000ms之后isStateChanged从moveToNewState方法中调用方法.
您正在寻找的是一种将值绑定this到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);
},
Run Code Online (Sandbox Code Playgroud)
以上是使用闭包来绑定上下文(请参阅:闭包不复杂),这是执行此操作的常用方法.Dojo可以提供内置函数来生成这些"绑定"回调(Prototype和jQuery do).(编辑:确实如此,在他的评论下面,peller好心地指出dojo.hitch.)
关于这个一般概念的更多信息:你必须记住this
| 归档时间: |
|
| 查看次数: |
9424 次 |
| 最近记录: |