使用间隔

时间:2016-12-20 21:20:56

标签: jquery jquery-ui

我想创建一个Jquery UI小部件,在创建时启动间隔。每个间隔超时调用的函数应该是可重写的,因此放在options对象中。

我可以从小部件外部开始间隔,我可以从小部件外部调用可重写的函数。但是当间隔尝试调用可重写函数时,它是undefined

这是我的小部件:

jQuery.widget("awesome.me", {
    options: {
        verbose:false,                        // just some setting
        onTimeOut: function(){                // this is the function that is called by the timeout and that should be overrideable 
            console.log("on timeOut called");
        }
    },
    _create: function(){
        console.log(this.options);            // logging the options object
    }, 
    _members: {                               // a private object to hold internal settings and stuff, for example the interval instance
        interval: null
    },
    start: function(){        
        this._members.interval = setInterval(this.doIt, 2000);
    },
    stop: function(){
        clearInterval(this._members.interval);
    },
    doIt: function(){
        console.log(this.options);            // here I would like to call my onTimeOut function, but the options are undefined, because THIS is undefined
    }
});

从外部,在脚本中我这样做来实例化我的小部件并开始间隔:

$(document).me();                              // I am not overriding the function for now
var widget = $(document).data("awesome-me");   // to facilitate access to my widget I grab the instance and put it in a normal variable
widget.start();                                // start() will set the interval

如果我在哪里拨打widget.doIt(),控制台会显示如下内容:

 Object {classes: Object, disabled: false, create: null, verbose: false}

但是当我运行脚本时,每两秒钟会出现一次:

undefined

根据我的理解,当我调用widget.start()时,间隔将每隔2秒开始调用this.doIt,但在doIt函数内,当它尝试记录{{1}时对象,它消失了。所以我的options变量仍然具有我的小部件的正确实例,我可以调用我想要的每个函数。但是当间隔超时时,它会保存函数widget存在的其他窗口小部件实例,但doIt未定义。

我不明白的是:为什么?我怎么解决这个问题?

1 个答案:

答案 0 :(得分:2)

问题在于this._members.interval = setInterval(this.doIt, 2000);

this.doIt被调用时,thiswindow调用,而window.options实际上是doItconsole.log(this)正在访问doIt doIt this查看this._members.interval = setInterval(this.doIt.bind(this), 2000); 运行时的内容。

修复方法是绑定或执行var self = this; this._members.interval = setInterval(function(){self.doIt();}, 2000); 传递Set pdDoc = avDoc.GetPDDoc() Set jso = pdDoc.GetJSObject jso.getField("buttonImage1")..BorderStyle = "beveled" jso.getField("buttonImage1").buttonImportIcon CStr(photoSet!Photo) jso.getField("caption1").Value = CStr(photoSet!Caption) jso.getField("buttonImage1").ButtonLayout = "1" 'This is the only line that doesn't work

out_color_space

cinfo