简体   繁体   中英

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

I want to define a javascript class, instantiate an instance of it in my html page and have the class set a click handler that then uses setTimeout(...) to call a member function of the class.

This is currently not working out for me as I have a hard time understanding the correct way to scope my class and/or calls and usage of the object created. I hope someone might be able to help me out with the example below.

The below code has a few references to $(...) which is jquery, just to clarify for anyone that might read this and not recognize it.

I use the following as a base for a class in my JavaScript code:

// 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;
};

I then expand on this with my class in JavaScript as well:

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');
    }
});

And my HTML looks like this:

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

The question is, how can I make the two calls to myFunction work from within the click handler which is called when I click on the "searchclear" HTML object?

Have you tried:?

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');
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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