繁体   English   中英

从类中设置的点击处理程序中使用setTimeout调用javascript类函数

[英]Calling javascript class function with setTimeout from click handler set within the class

我想定义一个javascript类,在html页面中实例化它的实例,并让该类设置一个单击处理程序,然后使用setTimeout(...)来调用该类的成员函数。

目前,这对我来说还行不通,因为我很难理解确定类和/或调用以及所创建对象的用法的正确方法。 我希望有人可以通过以下示例为我提供帮助。

下面的代码对$(...)这是jquery进行了一些引用,目的是为了澄清可能读过它但无法识别它的任何人。

我将以下内容用作JavaScript代码中类的基础:

// Taken from http://www.htmlgoodies.com/html5/tutorials/create-an-object-oriented-javascript-class-constructor.html
// Base class from which we can derive our own classes with ease
var Class = function (methods) {
    var klass = function () {
        this.initialize.apply(this, arguments);
    };

    for (var property in methods) {
        klass.prototype[property] = methods[property];
    }

    if (!klass.prototype.initialize) klass.prototype.initialize = function () { };

    return klass;
};

然后,我也使用我的JavaScript类对此进行扩展:

var myNamespace = myNamespace || {};

myNamespace.myClass = Class({
    somevalue: 100,

    initialize: function(somevalue) {
        this.somevalue = somevalue;

        $("#searchclear").click(function () {
            setTimeout(myFunction,1000); // THIS DOES NOT WORK as the context is now the searchclear html element
            myFunction(); // For completeness, this would not work either for the same reason
        });
    }),

    myFunction: function() {
        alert('we are ok');
    }
});

我的HTML看起来像这样:

<body>
    ...
    <script>
        $(document).ready(function () {
            var myInstance = new myNamespace.myClass(123);
        });
    </script>
    <span id='searchclear'>CLICK ME</span>
    ...
</body>

问题是,如何在单击“ searchclear” HTML对象时被调用的单击处理程序中对myFunction进行两次调用?

你有没有尝试过:?

myNamespace.myClass = Class({
    somevalue: 100,

    var self = this;

    initialize: function(somevalue) {
        this.somevalue = somevalue;

        $("#searchclear").click(function () {
            setTimeout(self.myFunction,1000); // THIS DOES NOT WORK as the context is now the searchclear html element
            self.myFunction(); // For completeness, this would not work either for the same reason
        });
    }),

    self.myFunction: function() {
        alert('we are ok');
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM