javascript - 在dojo类中调用JavaScript的setTimeOut

标签 javascript dojo settimeout

我正在尝试将我的 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/

相关文章:

javascript - iOS Safari 内存泄漏导致应用程序无法使用

javascript - 使用动画和滚动时闪烁

javascript - DOJO 工具提示给出 "Uncaught TypeError: object is not a function "

java - 是否有为 Spring 3 REST Controller 生成 JSON SMD 的解决方案?

javascript - safari 和 chrome javascript 控制台多行

JavaScript - 排序选择选项

javascript - 分离 Spring 和 Dojo 单页应用程序代码库

javascript - 当页面不活动时停止 setTimeout 循环,当页面事件时重新启动

Swift Alamofire 检查等待超时并放置错误

css - 谷歌地图调整大小 : maptype control button css style disappears