我正在尝试将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");

请让我知道如何在2000ms之后从isStateChanged方法调用moveToNewState方法。

最佳答案

您正在寻找的是一种将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/

10-12 00:25
查看更多