Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Undefined variable in keypress event

I have this code in my project, that uses Prototype 1.7.1

var Worker = Class.create({
    initialize: function() {
        this.ap = $('ap');

        alert( this.ap.value );

        $( 'main-form' ).on( 'change', '.inputs', this.recount );
        this.ap.observe( 'keypress', this.recount );
    },
    recount: function() {
        alert( this.ap.value );
    }
});
document.observe('dom:loaded', function(){
    var w = new Worker();
});

Item of id="ap" is text input field inside a form. Inside above class initializer, #ap element is found, this.ap member is assigned ( alert shows correct value ).

Now, when I change #ap input value, recount method called by keypress event gives me an error - this.ap is undefined. After I click outside of this input, to loose focus, recount method called by change event works correctly ( this.ap is assigned ).

like image 890
Soul Reaver Avatar asked Aug 26 '26 15:08

Soul Reaver


1 Answers

Sure, the handler will be executed in context of the DOM element - this does not point to your Worker instance. Use

$( 'main-form' ).on( 'change', '.inputs', this.recount.bind(this) );

Btw, it is not a good idea to name your class "Worker" - this would overwrite the global WebWorker constructor.

like image 92
Bergi Avatar answered Aug 28 '26 06:08

Bergi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!