Question

I have an event firing and even though it's inside of the function from which I'm trying to access variables, I get Uncaught TypeError: Cannot read property '...' of undefined. So, let's say:

( function($) {

    $.fn.main = function() {

        this.setting = 1;

        $("#someElement").scroll( function() {

            console.debug(this.setting);

        } );

    }

} )(jQuery);

I'm sure it has something to do with timing, but then again, I could be wrong. Should I make a copy of this and make that public? Anyone? Thanks.

Était-ce utile?

La solution

The value of this cannot be pinned in a closure as the this gets its value dynamically.

try :

var self = this;

And reference self.

Autres conseils

Just copy this to another variable

( function($) {

    $.fn.main = function() {

        this.setting = 1;
        var that = this;
        $("#someElement").scroll( function() {

            console.debug(that.setting);

        } );

    }

} )(jQuery);
( function($) {

    $.fn.main = function() {

        this.setting = 1; // "this" refers to the "$.fn.main" object

        $("#someElement").scroll( function() {

            console.debug(this.setting); // "this" refers to the "$('#someElement')" object

        } );

    }

} )(jQuery);

If you want to use the this from $.fn.main, you can store the variable. The following would work:

( function($) {

    $.fn.main = function() {

        var that = this

        that.setting = 1; // "this.setting" would also work

        $("#someElement").scroll( function() {

            console.debug(that.setting); // You need to reference to the other "this"

        } );

    }

} )(jQuery);

the this inside the scroll method is refereing to the scroll method. The method is bound to be called on the scroll event of element with id 'someElement'. and the scope of the binding object is lost.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top