Search code examples
javascriptprototypejs

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 ).


Solution

  • 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.